每次发布项目都要重新部署服务器,是否已经让你厌恶?项目发布能不能连同运行环境一起自动化部署?为了解决这个问题,docker出现了。
docker的灵感来自于集装箱,重点在于隔离机制,通过隔离机制能做到避免多个应用的端口冲突,实现单台服务器部署多个运行环境。
诞生于2010年,几个搞IT的热血青年走到一起创办了dotCloud公司;
起初由于代码不开源,行业内并没有太多人使用docker;
2013年,docker决定开放源代码,随后使用docker的人越来越多;
docker是一种虚拟技术,但又不同于VMware,它是一种容器技术,比虚拟机要轻量得多。
环境:centOS 7
# 以下内容为操作系统具体信息
uname -r
3.10.0-1160.el7.x86_64
cat /etc/redhat-release
CentOS Linux release 7.9.2009 (Core)
# 1.卸载旧版本docker
[root@localhost ~]# yum remove docker \
> docker-client \
> docker-client-latest \
> docker-common \
> docker-latest \
> docker-latest-logrotate \
> docker-logrotate \
> docker-engine
Loaded plugins: fastestmirror
No Match for argument: docker
No Match for argument: docker-client
No Match for argument: docker-client-latest
No Match for argument: docker-common
No Match for argument: docker-latest
No Match for argument: docker-latest-logrotate
No Match for argument: docker-logrotate
No Match for argument: docker-engine
No Packages marked for removal
# 2.安装yum相关的安装包
[root@localhost lib]# yum install yum-utils
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
* base: mirrors.aliyun.com
* extras: mirrors.aliyun.com
* updates: mirrors.aliyun.com
Package yum-utils-1.1.31-54.el7_8.noarch already installed and latest version
Nothing to do
# 3.设置镜像仓库(此处最好用国内镜像,国外镜像速度不稳定)
[root@localhost lib]# yum-config-manager \
> --add-repo \
> http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
Loaded plugins: fastestmirror
adding repo from: http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
grabbing file http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo to /etc/yum.repos.d/docker-ce.repo
repo saved to /etc/yum.repos.d/docker-ce.repo
# 4.安装docker相关安装包
[root@localhost lib]# yum install docker-ce docker-ce-cli containerd.io
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
* base: mirrors.aliyun.com
* extras: mirrors.aliyun.com
* updates: mirrors.aliyun.com
docker-ce-stable | 3.5 kB 00:00:00
(1/2): docker-ce-stable/7/x86_64/primary_db | 55 kB 00:00:03
(2/2): docker-ce-stable/7/x86_64/updateinfo | 55 B 00:00:03
Resolving Dependencies
--> Running transaction check
---> Package containerd.io.x86_64 0:1.4.3-3.1.el7 will be installed
--> Processing Dependency: container-selinux >= 2:2.74 for package: containerd.io-1.4.3-3.1.el7.x86_64
--> Processing Dependency: libseccomp for package: containerd.io-1.4.3-3.1.el7.x86_64
---> Package docker-ce.x86_64 3:20.10.3-3.el7 will be installed
--> Processing Dependency: docker-ce-rootless-extras for package: 3:docker-ce-20.10.3-3.el7.x86_64
---> Package docker-ce-cli.x86_64 1:20.10.3-3.el7 will be installed
--> Running transaction check
---> Package container-selinux.noarch 2:2.119.2-1.911c772.el7_8 will be installed
---> Package docker-ce-rootless-extras.x86_64 0:20.10.3-3.el7 will be installed
--> Processing Dependency: fuse-overlayfs >= 0.7 for package: docker-ce-rootless-extras-20.10.3-3.el7.x86_64
--> Processing Dependency: slirp4netns >= 0.4 for package: docker-ce-rootless-extras-20.10.3-3.el7.x86_64
---> Package libseccomp.x86_64 0:2.3.1-4.el7 will be installed
--> Running transaction check
---> Package fuse-overlayfs.x86_64 0:0.7.2-6.el7_8 will be installed
--> Processing Dependency: libfuse3.so.3(FUSE_3.2)(64bit) for package: fuse-overlayfs-0.7.2-6.el7_8.x86_64
--> Processing Dependency: libfuse3.so.3(FUSE_3.0)(64bit) for package: fuse-overlayfs-0.7.2-6.el7_8.x86_64
--> Processing Dependency: libfuse3.so.3()(64bit) for package: fuse-overlayfs-0.7.2-6.el7_8.x86_64
---> Package slirp4netns.x86_64 0:0.4.3-4.el7_8 will be installed
--> Running transaction check
---> Package fuse3-libs.x86_64 0:3.6.1-4.el7 will be installed
--> Finished Dependency Resolution
Dependencies Resolved
================================================================================================================================================================================
Package Arch Version Repository Size
================================================================================================================================================================================
Installing:
containerd.io x86_64 1.4.3-3.1.el7 docker-ce-stable 33 M
docker-ce x86_64 3:20.10.3-3.el7 docker-ce-stable 27 M
docker-ce-cli x86_64 1:20.10.3-3.el7 docker-ce-stable 33 M
Installing for dependencies:
container-selinux noarch 2:2.119.2-1.911c772.el7_8 extras 40 k
docker-ce-rootless-extras x86_64 20.10.3-3.el7 docker-ce-stable 9.0 M
fuse-overlayfs x86_64 0.7.2-6.el7_8 extras 54 k
fuse3-libs x86_64 3.6.1-4.el7 extras 82 k
libseccomp x86_64 2.3.1-4.el7 base 56 k
slirp4netns x86_64 0.4.3-4.el7_8 extras 81 k
Transaction Summary
================================================================================================================================================================================
Install 3 Packages (+6 Dependent packages)
Total download size: 102 M
Installed size: 423 M
Is this ok [y/d/N]: y
Downloading packages:
(1/9): container-selinux-2.119.2-1.911c772.el7_8.noarch.rpm | 40 kB 00:00:00
warning: /var/cache/yum/x86_64/7/docker-ce-stable/packages/docker-ce-20.10.3-3.el7.x86_64.rpm: Header V4 RSA/SHA512 Signature, key ID 621e9f35: NOKEYB/s | 30 MB 00:00:20 ETA
Public key for docker-ce-20.10.3-3.el7.x86_64.rpm is not installed
(2/9): docker-ce-20.10.3-3.el7.x86_64.rpm | 27 MB 00:00:08
(3/9): docker-ce-cli-20.10.3-3.el7.x86_64.rpm | 33 MB 00:00:09
(4/9): fuse-overlayfs-0.7.2-6.el7_8.x86_64.rpm | 54 kB 00:00:00
(5/9): slirp4netns-0.4.3-4.el7_8.x86_64.rpm | 81 kB 00:00:00
(6/9): fuse3-libs-3.6.1-4.el7.x86_64.rpm | 82 kB 00:00:00
(7/9): libseccomp-2.3.1-4.el7.x86_64.rpm | 56 kB 00:00:00
(8/9): docker-ce-rootless-extras-20.10.3-3.el7.x86_64.rpm | 9.0 MB 00:00:02
(9/9): containerd.io-1.4.3-3.1.el7.x86_64.rpm | 33 MB 00:00:25
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Total 4.0 MB/s | 102 MB 00:00:25
Retrieving key from https://download.docker.com/linux/centos/gpg
Importing GPG key 0x621E9F35:
Userid : "Docker Release (CE rpm) <docker@docker.com>"
Fingerprint: 060a 61c5 1b55 8a7f 742b 77aa c52f eb6b 621e 9f35
From : https://download.docker.com/linux/centos/gpg
Is this ok [y/N]: y
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
Installing : libseccomp-2.3.1-4.el7.x86_64 1/9
Installing : 2:container-selinux-2.119.2-1.911c772.el7_8.noarch 2/9
Installing : containerd.io-1.4.3-3.1.el7.x86_64 3/9
Installing : slirp4netns-0.4.3-4.el7_8.x86_64 4/9
Installing : 1:docker-ce-cli-20.10.3-3.el7.x86_64 5/9
Installing : fuse3-libs-3.6.1-4.el7.x86_64 6/9
Installing : fuse-overlayfs-0.7.2-6.el7_8.x86_64 7/9
Installing : 3:docker-ce-20.10.3-3.el7.x86_64 8/9
Installing : docker-ce-rootless-extras-20.10.3-3.el7.x86_64 9/9
Verifying : fuse3-libs-3.6.1-4.el7.x86_64 1/9
Verifying : 3:docker-ce-20.10.3-3.el7.x86_64 2/9
Verifying : fuse-overlayfs-0.7.2-6.el7_8.x86_64 3/9
Verifying : slirp4netns-0.4.3-4.el7_8.x86_64 4/9
Verifying : 2:container-selinux-2.119.2-1.911c772.el7_8.noarch 5/9
Verifying : libseccomp-2.3.1-4.el7.x86_64 6/9
Verifying : containerd.io-1.4.3-3.1.el7.x86_64 7/9
Verifying : docker-ce-rootless-extras-20.10.3-3.el7.x86_64 8/9
Verifying : 1:docker-ce-cli-20.10.3-3.el7.x86_64 9/9
Installed:
containerd.io.x86_64 0:1.4.3-3.1.el7 docker-ce.x86_64 3:20.10.3-3.el7 docker-ce-cli.x86_64 1:20.10.3-3.el7
Dependency Installed:
container-selinux.noarch 2:2.119.2-1.911c772.el7_8 docker-ce-rootless-extras.x86_64 0:20.10.3-3.el7 fuse-overlayfs.x86_64 0:0.7.2-6.el7_8 fuse3-libs.x86_64 0:3.6.1-4.el7
libseccomp.x86_64 0:2.3.1-4.el7 slirp4netns.x86_64 0:0.4.3-4.el7_8
Complete!
# 5.查看docker 版本
[root@localhost lib]# docker version
Client: Docker Engine - Community
Version: 20.10.3
API version: 1.41
Go version: go1.13.15
Git commit: 48d30b5
Built: Fri Jan 29 14:34:14 2021
OS/Arch: linux/amd64
Context: default
Experimental: true
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
# 6.启动docker
[root@localhost lib]# systemctl start docker
# 7.运行hello-world镜像
[root@localhost lib]# docker run hello-world
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
0e03bdcc26d7: Pull complete
Digest: sha256:95ddb6c31407e84e91a986b004aee40975cb0bda14b5949f6faac5d2deadb4b9
Status: Downloaded newer image for hello-world:latest
Hello from Docker!
This message shows that your installation appears to be working correctly.
To generate this message, Docker took the following steps:
1. The Docker client contacted the Docker daemon.
2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
(amd64)
3. The Docker daemon created a new container from that image which runs the
executable that produces the output you are currently reading.
4. The Docker daemon streamed that output to the Docker client, which sent it
to your terminal.
To try something more ambitious, you can run an Ubuntu container with:
$ docker run -it ubuntu bash
Share images, automate workflows, and more with a free Docker ID:
https://hub.docker.com/
For more examples and ideas, visit:
https://docs.docker.com/get-started/
# 8.查看hello-world镜像
[root@localhost docker]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
hello-world latest bf756fb1ae65 13 months ago 13.3kB
如需卸载可执行以下命令
yum remove docker-ce docker-ce-cli containerd.io
rm -rf /var/lib/docker
[root@localhost ~]# docker info
Client:
Context: default
Debug Mode: false
Plugins:
app: Docker App (Docker Inc., v0.9.1-beta3)
buildx: Build with BuildKit (Docker Inc., v0.5.1-docker)
Server:
Containers: 2
Running: 0
Paused: 0
Stopped: 2
Images: 1
Server Version: 20.10.3
Storage Driver: overlay2
Backing Filesystem: xfs
Supports d_type: true
Native Overlay Diff: true
Logging Driver: json-file
Cgroup Driver: cgroupfs
Cgroup Version: 1
Plugins:
Volume: local
Network: bridge host ipvlan macvlan null overlay
Log: awslogs fluentd gcplogs gelf journald json-file local logentries splunk syslog
Swarm: inactive
Runtimes: io.containerd.runc.v2 io.containerd.runtime.v1.linux runc
Default Runtime: runc
Init Binary: docker-init
containerd version: 269548fa27e0089a8b8278fc4fc781d7f65a939b
runc version: ff819c7e9184c13b7c2607fe6c30ae19403a7aff
init version: de40ad0
Security Options:
seccomp
Profile: default
Kernel Version: 3.10.0-1160.el7.x86_64
Operating System: CentOS Linux 7 (Core)
OSType: linux
Architecture: x86_64
CPUs: 1
Total Memory: 991.3MiB
Name: localhost.localdomain
ID: J6FX:JPAO:CN55:Z27Y:35FS:7LIE:NNJX:FDPN:REID:74WW:GT66:OZJM
Docker Root Dir: /var/lib/docker
Debug Mode: false
Registry: https://index.docker.io/v1/
Labels:
Experimental: false
Insecure Registries:
127.0.0.0/8
Live Restore Enabled: false
[root@localhost ~]# docker version
Client: Docker Engine - Community
Version: 20.10.3
API version: 1.41
Go version: go1.13.15
Git commit: 48d30b5
Built: Fri Jan 29 14:34:14 2021
OS/Arch: linux/amd64
Context: default
Experimental: true
Server: Docker Engine - Community
Engine:
Version: 20.10.3
API version: 1.41 (minimum version 1.12)
Go version: go1.13.15
Git commit: 46229ca
Built: Fri Jan 29 14:32:37 2021
OS/Arch: linux/amd64
Experimental: false
containerd:
Version: 1.4.3
GitCommit: 269548fa27e0089a8b8278fc4fc781d7f65a939b
runc:
Version: 1.0.0-rc92
GitCommit: ff819c7e9184c13b7c2607fe6c30ae19403a7aff
docker-init:
Version: 0.19.0
GitCommit: de40ad0
[root@localhost ~]# docker --help
Usage: docker [OPTIONS] COMMAND
A self-sufficient runtime for containers
Options:
--config string Location of client config files (default "/root/.docker")
-c, --context string Name of the context to use to connect to the daemon (overrides DOCKER_HOST env var and default context set with "docker context use")
-D, --debug Enable debug mode
-H, --host list Daemon socket(s) to connect to
-l, --log-level string Set the logging level ("debug"|"info"|"warn"|"error"|"fatal") (default "info")
--tls Use TLS; implied by --tlsverify
--tlscacert string Trust certs signed only by this CA (default "/root/.docker/ca.pem")
--tlscert string Path to TLS certificate file (default "/root/.docker/cert.pem")
--tlskey string Path to TLS key file (default "/root/.docker/key.pem")
--tlsverify Use TLS and verify the remote
-v, --version Print version information and quit
Management Commands:
app* Docker App (Docker Inc., v0.9.1-beta3)
builder Manage builds
buildx* Build with BuildKit (Docker Inc., v0.5.1-docker)
config Manage Docker configs
container Manage containers
context Manage contexts
image Manage images
manifest Manage Docker image manifests and manifest lists
network Manage networks
node Manage Swarm nodes
plugin Manage plugins
secret Manage Docker secrets
service Manage services
stack Manage Docker stacks
swarm Manage Swarm
system Manage Docker
trust Manage trust on Docker images
volume Manage volumes
Commands:
attach Attach local standard input, output, and error streams to a running container
build Build an image from a Dockerfile
commit Create a new image from a container's changes
cp Copy files/folders between a container and the local filesystem
create Create a new container
diff Inspect changes to files or directories on a container's filesystem
events Get real time events from the server
exec Run a command in a running container
export Export a container's filesystem as a tar archive
history Show the history of an image
images List images
import Import the contents from a tarball to create a filesystem image
info Display system-wide information
inspect Return low-level information on Docker objects
kill Kill one or more running containers
load Load an image from a tar archive or STDIN
login Log in to a Docker registry
logout Log out from a Docker registry
logs Fetch the logs of a container
pause Pause all processes within one or more containers
port List port mappings or a specific mapping for the container
ps List containers
pull Pull an image or a repository from a registry
push Push an image or a repository to a registry
rename Rename a container
restart Restart one or more containers
rm Remove one or more containers
rmi Remove one or more images
run Run a command in a new container
save Save one or more images to a tar archive (streamed to STDOUT by default)
search Search the Docker Hub for images
start Start one or more stopped containers
stats Display a live stream of container(s) resource usage statistics
stop Stop one or more running containers
tag Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE
top Display the running processes of a container
unpause Unpause all processes within one or more containers
update Update configuration of one or more containers
version Show the Docker version information
wait Block until one or more containers stop, then print their exit codes
Run 'docker COMMAND --help' for more information on a command.
To get more help with docker, check out our guides at https://docs.docker.com/go/guides/
以安装mysql为例进行操作:
# docker search 命令可以搜索镜像
[root@localhost ~]# docker search mysql
NAME DESCRIPTION STARS OFFICIAL AUTOMATED
mysql MySQL is a widely used, open-source relation… 10534 [OK]
mariadb MariaDB is a community-developed fork of MyS… 3934 [OK]
mysql/mysql-server Optimized MySQL Server Docker images. Create… 773 [OK]
percona Percona Server is a fork of the MySQL relati… 527 [OK]
centos/mysql-57-centos7 MySQL 5.7 SQL database server 86
mysql/mysql-cluster Experimental MySQL Cluster Docker images. Cr… 79
centurylink/mysql Image containing mysql. Optimized to be link… 59 [OK]
bitnami/mysql Bitnami MySQL Docker Image 48 [OK]
deitch/mysql-backup REPLACED! Please use http://hub.docker.com/r… 41 [OK]
databack/mysql-backup Back up mysql databases to... anywhere! 38
prom/mysqld-exporter 37 [OK]
tutum/mysql Base docker image to run a MySQL database se… 35
schickling/mysql-backup-s3 Backup MySQL to S3 (supports periodic backup… 29 [OK]
linuxserver/mysql A Mysql container, brought to you by LinuxSe… 27
centos/mysql-56-centos7 MySQL 5.6 SQL database server 20
circleci/mysql MySQL is a widely used, open-source relation… 20
mysql/mysql-router MySQL Router provides transparent routing be… 18
arey/mysql-client Run a MySQL client from a docker container 17 [OK]
fradelg/mysql-cron-backup MySQL/MariaDB database backup using cron tas… 11 [OK]
yloeffler/mysql-backup This image runs mysqldump to backup data usi… 7 [OK]
openshift/mysql-55-centos7 DEPRECATED: A Centos7 based MySQL v5.5 image… 6
devilbox/mysql Retagged MySQL, MariaDB and PerconaDB offici… 3
ansibleplaybookbundle/mysql-apb An APB which deploys RHSCL MySQL 2 [OK]
jelastic/mysql An image of the MySQL database server mainta… 1
widdpim/mysql-client Dockerized MySQL Client (5.7) including Curl… 1 [OK]
# docker pull命令可以拉取镜像
# docker pull mysql等同于docker pull mysql:latest
# 还可以指定版本进行拉取docker pull mysql:5.7
[root@localhost ~]# docker pull mysql
Using default tag: latest
latest: Pulling from library/mysql
45b42c59be33: Pull complete
b4f790bd91da: Pull complete
325ae51788e9: Pull complete
adcb9439d751: Pull complete
174c7fe16c78: Pull complete
698058ef136c: Pull complete
4690143a669e: Pull complete
f7599a246fd6: Pull complete
35a55bf0c196: Downloading [============================> ] 63.76MB/113.1MB
790ac54f4c47: Download complete
18602acc97e1: Download complete
365caa3500d0: Waiting
[root@localhost ~]# docker pull mysql:5.7
5.7: Pulling from library/mysql
45b42c59be33: Already exists # docker的强大之处在于采用了这种分层机制,上一次命令中已经拉取了最新版本的mysql,即便以后再拉取其他版本的mysql,可重用层的镜像无需重新拉取。
b4f790bd91da: Already exists
325ae51788e9: Already exists
adcb9439d751: Already exists
174c7fe16c78: Already exists
698058ef136c: Already exists
4690143a669e: Already exists
66676c1ab9b3: Pull complete
25ebf78a38b6: Downloading [==============================================> ] 101.3MB/108.4MB
349a839d5e27: Download complete
40b03e3e5980: Download complete
# docker images 列出所有已拉取的镜像
[root@localhost ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
mysql 5.7 5f47254ca581 2 weeks ago 449MB
mysql latest 2933adc350f3 2 weeks ago 546MB
hello-world latest bf756fb1ae65 13 months ago 13.3kB
# 如果想删除已拉取的镜像只需执行docker rmi 【IMAGE ID】即可
[root@localhost ~]# docker rmi 5f47254ca581
Untagged: mysql:5.7
Untagged: mysql@sha256:853105ad984a9fe87dd109be6756e1fbdba8b003b303d88ac0dda6b455f36556
Deleted: sha256:5f47254ca5817f99cdd387ce7345d43e770e0682a4c81b62776f3347551b1d85
Deleted: sha256:63f5d2725ff0ecffe0a7345e749d39b269a8cef04984661f0f4e752869b9fbb1
Deleted: sha256:acbe85abff4e7bbdd75a1f56ee9a095a72fcba4c226d0194d46b9a8471b1fe18
Deleted: sha256:b851a484b18c5d3d25497260c111631ae3adf924eb10baa533b2a5b03b339d1a
Deleted: sha256:b5133b076285236e7fd98c42c1f18f57e2b4ed98daaed7b0afb3b98b804d6f25
# 可以看到执行了上述命令后,成功删除了mysql:5.7
[root@localhost ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
mysql latest 2933adc350f3 2 weeks ago 546MB
hello-world latest bf756fb1ae65 13 months ago 13.3kB
# 此外还可以以传参的形式进行批量删除,以下命令将返回所有已拉取镜像的IMAGE ID,将此命令以变量形式传入docker rmi,继续进行下面的操作
[root@localhost ~]# docker images -qa
2933adc350f3
bf756fb1ae65
[root@localhost ~]# docker rmi $(docker images -qa)
Untagged: mysql:latest
Untagged: mysql@sha256:b1cc887ed32cc6c2f217b12703bd05f503f2037892c8bb226047fe5dff85a109
Deleted: sha256:2933adc350f3b62c05a66f700fba68ef93997d67263121250ec7848c50dcf3f5
Deleted: sha256:78b6531a3acdad2154a839ac1ec9ae2677632cc834bd996e75317f6e35717834
Deleted: sha256:f0c1c423000a6848e30ae3249c25b16f678167e56b4bb3013445b2ad1d179e8c
Deleted: sha256:4386f82820992c927b924177ed3e4c2ffd477d4db7a63539ac76fd09ee36cd89
Deleted: sha256:d7494c9168a11444d8b13558068409ace7393452f08f878686eec45122ee56c1
Deleted: sha256:08dbcab3fe630e39bbabaa9f0ae72ec6d100bf1e400ebb4b7f04151b18bca89c
Deleted: sha256:c3f78dcd6bcc4c156554296323e0eed74a4d2d93b304be15f55c1ef62dd06e0a
Deleted: sha256:f89b66495a65489290c8edb71e0dbf9e3d0d6213b82cebc2554b271599f2f99d
Deleted: sha256:1918839317d9988ff5e0168e336717e32820af1e77c3121297efc73a387ecdc5
Deleted: sha256:1d2bcd52664a92805e5f49d94d3649323dd0f5682ae3e1380fa07b7a54d6ceb0
Deleted: sha256:787de05fee96c7ba99e49f17d72aec68769a7373a8881a27917bdbf83dca58e8
Deleted: sha256:eb82f9a2fbd7a4a0fdfbe40b5e77a995ccf73ab91364d90f4db820fd59dbf63b
Deleted: sha256:9eb82f04c782ef3f5ca25911e60d75e441ce0fe82e49f0dbf02c81a3161d1300
Error response from daemon: conflict: unable to delete bf756fb1ae65 (must be forced) - image is being used by stopped container 0c7703f6e04d # 由于hello-world已被使用,若仍想删除需要使用-f强制删除
[root@localhost ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
hello-world latest bf756fb1ae65 13 months ago 13.3kB # 未删除成功
[root@localhost ~]# docker rmi -f $(docker images -qa)
Untagged: hello-world:latest
Untagged: hello-world@sha256:95ddb6c31407e84e91a986b004aee40975cb0bda14b5949f6faac5d2deadb4b9
Deleted: sha256:bf756fb1ae65adf866bd8c456593cd24beb6a0a061dedf42b26a993176745f6b # 加上-f参数后,删除成功
[root@localhost ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
[root@localhost ~]#
注意:镜像是创建容器的前提。
# 下载一个centos镜像并以docker进行安装
[root@localhost ~]# docker pull centos
Using default tag: latest
latest: Pulling from library/centos
7a0437f04f83: Downloading [=====================> ] 31.63MB/75.18MB
[root@localhost ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
centos latest 300e315adb2f 2 months ago 209MB
[root@localhost ~]# docker run -it centos /bin/bash
[root@7769890c1d06 /]# 此处的主机名已经变成新安装的centos,说明已经进入了centos容器
# doker内部的centos系统和宿主机是完全隔离的
[root@7769890c1d06 /]# exit
exit # 执行exit命令可以从容器回到宿主机,此时容器也会停止运行,如果希望退出容器但不停止容器运行可以【CTRL+P+Q】
[root@localhost ~]#
# docker ps可以查看正在运行的容器,而docker ps -a可以查看所有(包括正在运行和运行过的容器)
[root@localhost ~]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
7769890c1d06 centos "/bin/bash" 5 minutes ago Exited (127) About a minute ago ecstatic_johnson
b62415cd50c2 bf756fb1ae65 "/hello" About an hour ago Exited (0) About an hour ago quizzical_cray
0c7703f6e04d bf756fb1ae65 "/hello" 17 hours ago Exited (0) 17 hours ago zealous_poitras
# 如果需要删除容器,方法和删除镜像类似docker rm 【CONTAINER ID】或者传参进行批量删除
[root@localhost ~]# docker rm $(docker ps -qa) 可以看到,执行此命令会连同运行的历史容器信息一同删除,当然此处也可以使用docker ps -qa | xargs docker rm来进行批量删除
7769890c1d06
b62415cd50c2
0c7703f6e04d
[root@localhost ~]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
[root@localhost ~]#
# 容器启动停止命令
# docker start/stop/restart/kill 【CONTAINER ID】
[root@localhost ~]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
e887b4b948ff centos "/bin/bash" 57 seconds ago Exited (0) 22 seconds ago goofy_mendel
[root@localhost ~]# docker start e887b4b948ff
e887b4b948ff
[root@localhost ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
e887b4b948ff centos "/bin/bash" About a minute ago Up 2 seconds goofy_mendel
[root@localhost ~]# docker stop e887b4b948ff
e887b4b948ff
[root@localhost ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
[root@localhost ~]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
e887b4b948ff centos "/bin/bash" About a minute ago Exited (0) 6 seconds ago goofy_mendel
[root@localhost ~]# docker start e887b4b948ff
e887b4b948ff
[root@localhost ~]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
e887b4b948ff centos "/bin/bash" About a minute ago Up 3 seconds goofy_mendel
[root@localhost ~]# docker kill e887b4b948ff
e887b4b948ff
[root@localhost ~]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
e887b4b948ff centos "/bin/bash" 2 minutes ago Exited (137) 6 seconds ago goofy_mendel
[root@localhost ~]#
# docker -d 【镜像名】 后台运行容器,但从结果来看,容器启动之后立刻停止了,这是因为docker后台启动后必须要有一个对应的前台进程,如果没有找到,就会立刻停止运行。
[root@localhost ~]# docker run -d centos
60a8adaa8f1b657f8f7c154abd7e5b2b335471b638607cc7fe7104a803e309b1
[root@localhost ~]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
60a8adaa8f1b centos "/bin/bash" 7 seconds ago Exited (0) 6 seconds ago condescending_joliot
e887b4b948ff centos "/bin/bash" 12 minutes ago Exited (137) 11 minutes ago goofy_mendel
# docker inspect 命令可以查看容器的详细信息
[root@localhost ~]# docker inspect 60a8adaa8f1b
[
{
"Id": "60a8adaa8f1b657f8f7c154abd7e5b2b335471b638607cc7fe7104a803e309b1",
"Created": "2021-02-23T13:49:07.408650226Z",
"Path": "/bin/bash",
"Args": [],
"State": {
"Status": "exited",
"Running": false,
"Paused": false,
"Restarting": false,
"OOMKilled": false,
"Dead": false,
"Pid": 0,
"ExitCode": 0,
"Error": "",
"StartedAt": "2021-02-23T13:49:08.104622692Z",
"FinishedAt": "2021-02-23T13:49:08.103554234Z"
},
"Image": "sha256:300e315adb2f96afe5f0b2780b87f28ae95231fe3bdd1e16b9ba606307728f55",
"ResolvConfPath": "/var/lib/docker/containers/60a8adaa8f1b657f8f7c154abd7e5b2b335471b638607cc7fe7104a803e309b1/resolv.conf",
"HostnamePath": "/var/lib/docker/containers/60a8adaa8f1b657f8f7c154abd7e5b2b335471b638607cc7fe7104a803e309b1/hostname",
"HostsPath": "/var/lib/docker/containers/60a8adaa8f1b657f8f7c154abd7e5b2b335471b638607cc7fe7104a803e309b1/hosts",
"LogPath": "/var/lib/docker/containers/60a8adaa8f1b657f8f7c154abd7e5b2b335471b638607cc7fe7104a803e309b1/60a8adaa8f1b657f8f7c154abd7e5b2b335471b638607cc7fe7104a803e309b1-json.log",
"Name": "/condescending_joliot",
"RestartCount": 0,
"Driver": "overlay2",
"Platform": "linux",
"MountLabel": "",
"ProcessLabel": "",
"AppArmorProfile": "",
"ExecIDs": null,
"HostConfig": {
"Binds": null,
"ContainerIDFile": "",
"LogConfig": {
"Type": "json-file",
"Config": {}
},
"NetworkMode": "default",
"PortBindings": {},
"RestartPolicy": {
"Name": "no",
"MaximumRetryCount": 0
},
"AutoRemove": false,
"VolumeDriver": "",
"VolumesFrom": null,
"CapAdd": null,
"CapDrop": null,
"CgroupnsMode": "host",
"Dns": [],
"DnsOptions": [],
"DnsSearch": [],
"ExtraHosts": null,
"GroupAdd": null,
"IpcMode": "private",
"Cgroup": "",
"Links": null,
"OomScoreAdj": 0,
"PidMode": "",
"Privileged": false,
"PublishAllPorts": false,
"ReadonlyRootfs": false,
"SecurityOpt": null,
"UTSMode": "",
"UsernsMode": "",
"ShmSize": 67108864,
"Runtime": "runc",
"ConsoleSize": [
0,
0
],
"Isolation": "",
"CpuShares": 0,
"Memory": 0,
"NanoCpus": 0,
"CgroupParent": "",
"BlkioWeight": 0,
"BlkioWeightDevice": [],
"BlkioDeviceReadBps": null,
"BlkioDeviceWriteBps": null,
"BlkioDeviceReadIOps": null,
"BlkioDeviceWriteIOps": null,
"CpuPeriod": 0,
"CpuQuota": 0,
"CpuRealtimePeriod": 0,
"CpuRealtimeRuntime": 0,
"CpusetCpus": "",
"CpusetMems": "",
"Devices": [],
"DeviceCgroupRules": null,
"DeviceRequests": null,
"KernelMemory": 0,
"KernelMemoryTCP": 0,
"MemoryReservation": 0,
"MemorySwap": 0,
"MemorySwappiness": null,
"OomKillDisable": false,
"PidsLimit": null,
"Ulimits": null,
"CpuCount": 0,
"CpuPercent": 0,
"IOMaximumIOps": 0,
"IOMaximumBandwidth": 0,
"MaskedPaths": [
"/proc/asound",
"/proc/acpi",
"/proc/kcore",
"/proc/keys",
"/proc/latency_stats",
"/proc/timer_list",
"/proc/timer_stats",
"/proc/sched_debug",
"/proc/scsi",
"/sys/firmware"
],
"ReadonlyPaths": [
"/proc/bus",
"/proc/fs",
"/proc/irq",
"/proc/sys",
"/proc/sysrq-trigger"
]
},
"GraphDriver": {
"Data": {
"LowerDir": "/var/lib/docker/overlay2/9f92019e18d5193182529dbe96265189a436e9bd9aa680d96cc3c31eeba96872-init/diff:/var/lib/docker/overlay2/21c6f417179e27263e61af841c55dc09a4ef4d7cf0df76d1121201aca465a48a/diff",
"MergedDir": "/var/lib/docker/overlay2/9f92019e18d5193182529dbe96265189a436e9bd9aa680d96cc3c31eeba96872/merged",
"UpperDir": "/var/lib/docker/overlay2/9f92019e18d5193182529dbe96265189a436e9bd9aa680d96cc3c31eeba96872/diff",
"WorkDir": "/var/lib/docker/overlay2/9f92019e18d5193182529dbe96265189a436e9bd9aa680d96cc3c31eeba96872/work"
},
"Name": "overlay2"
},
"Mounts": [],
"Config": {
"Hostname": "60a8adaa8f1b",
"Domainname": "",
"User": "",
"AttachStdin": false,
"AttachStdout": false,
"AttachStderr": false,
"Tty": false,
"OpenStdin": false,
"StdinOnce": false,
"Env": [
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
],
"Cmd": [
"/bin/bash"
],
"Image": "centos",
"Volumes": null,
"WorkingDir": "",
"Entrypoint": null,
"OnBuild": null,
"Labels": {
"org.label-schema.build-date": "20201204",
"org.label-schema.license": "GPLv2",
"org.label-schema.name": "CentOS Base Image",
"org.label-schema.schema-version": "1.0",
"org.label-schema.vendor": "CentOS"
}
},
"NetworkSettings": {
"Bridge": "",
"SandboxID": "ae139fa3e5b4b1bcf73b4c7e91eca35efcc18c8bfba5a2f7c73e1c916d12a1fa",
"HairpinMode": false,
"LinkLocalIPv6Address": "",
"LinkLocalIPv6PrefixLen": 0,
"Ports": {},
"SandboxKey": "/var/run/docker/netns/ae139fa3e5b4",
"SecondaryIPAddresses": null,
"SecondaryIPv6Addresses": null,
"EndpointID": "",
"Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"IPAddress": "",
"IPPrefixLen": 0,
"IPv6Gateway": "",
"MacAddress": "",
"Networks": {
"bridge": {
"IPAMConfig": null,
"Links": null,
"Aliases": null,
"NetworkID": "39abe164fc6e3838e71772e53625d373d8955f2cdd096c40bc5b31085ae956b6",
"EndpointID": "",
"Gateway": "",
"IPAddress": "",
"IPPrefixLen": 0,
"IPv6Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"MacAddress": "",
"DriverOpts": null
}
}
}
}
]
[root@localhost ~]#
# docker exec 【CONTAINER ID】重新启动一个终端运行命令
# docker attach 【CONTAINER ID】打开已有终端运行命令
# 如果想把容器内的文件拷贝到宿主机可以参考如下步骤(反向也是可以的,并且无论容器进程启动与否都可成功):
[root@localhost ~]# docker run -it centos /bin/bash
[root@e2957ebb447c /]# ls
bin dev etc home lib lib64 lost+found media mnt opt proc root run sbin srv sys tmp usr var
[root@e2957ebb447c /]# cd home
[root@e2957ebb447c home]# ls
[root@e2957ebb447c home]# touch test.java
[root@e2957ebb447c home]# ls
test.java
[root@e2957ebb447c home]# ls
test.java
[root@e2957ebb447c home]# exit
exit
[root@localhost ~]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
e2957ebb447c centos "/bin/bash" About a minute ago Exited (0) 4 seconds ago quirky_meitner
60a8adaa8f1b centos "/bin/bash" 21 minutes ago Exited (0) 10 minutes ago condescending_joliot
e887b4b948ff centos "/bin/bash" 34 minutes ago Exited (137) 32 minutes ago goofy_mendel
[root@localhost ~]# docker cp e2957ebb447c:/home/test.java /home
[root@localhost ~]# cd /home
[root@localhost home]# ls
smbuser test.java
# 1. 搜索镜像 docker search nginx
[root@localhost home]# docker search nginx
NAME DESCRIPTION STARS OFFICIAL AUTOMATED
nginx Official build of Nginx. 14466 [OK]
jwilder/nginx-proxy Automated Nginx reverse proxy for docker con… 1968 [OK]
richarvey/nginx-php-fpm Container running Nginx + PHP-FPM capable of… 807 [OK]
jc21/nginx-proxy-manager Docker container for managing Nginx proxy ho… 150
linuxserver/nginx An Nginx container, brought to you by LinuxS… 141
tiangolo/nginx-rtmp Docker image with Nginx using the nginx-rtmp… 115 [OK]
jlesage/nginx-proxy-manager Docker container for Nginx Proxy Manager 95 [OK]
bitnami/nginx Bitnami nginx Docker Image 94 [OK]
alfg/nginx-rtmp NGINX, nginx-rtmp-module and FFmpeg from sou… 89 [OK]
nginxdemos/hello NGINX webserver that serves a simple page co… 66 [OK]
nginx/nginx-ingress NGINX Ingress Controller for Kubernetes 48
privatebin/nginx-fpm-alpine PrivateBin running on an Nginx, php-fpm & Al… 46 [OK]
nginxinc/nginx-unprivileged Unprivileged NGINX Dockerfiles 31
staticfloat/nginx-certbot Opinionated setup for automatic TLS certs lo… 19 [OK]
schmunk42/nginx-redirect A very simple container to redirect HTTP tra… 19 [OK]
centos/nginx-112-centos7 Platform for running nginx 1.12 or building … 15
nginx/nginx-prometheus-exporter NGINX Prometheus Exporter 15
centos/nginx-18-centos7 Platform for running nginx 1.8 or building n… 13
raulr/nginx-wordpress Nginx front-end for the official wordpress:f… 13 [OK]
flashspys/nginx-static Super Lightweight Nginx Image 9 [OK]
bitwarden/nginx The Bitwarden nginx web server acting as a r… 9
bitnami/nginx-ingress-controller Bitnami Docker Image for NGINX Ingress Contr… 8 [OK]
mailu/nginx Mailu nginx frontend 8 [OK]
ansibleplaybookbundle/nginx-apb An APB to deploy NGINX 2 [OK]
wodby/nginx Generic nginx 1 [OK]
[root@localhost home]#
# 2. 下载镜像 docker pull nginx
[root@localhost home]# docker pull nginx
Using default tag: latest
latest: Pulling from library/nginx
45b42c59be33: Pull complete
8acc495f1d91: Pull complete
ec3bd7de90d7: Pull complete
19e2441aeeab: Pull complete
f5a38c5f8d4e: Pull complete
83500d851118: Pull complete
Digest: sha256:f3693fe50d5b1df1ecd315d54813a77afd56b0245a404055a946574deb6b34fc
Status: Downloaded newer image for nginx:latest
docker.io/library/nginx:latest
[root@localhost home]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
nginx latest 35c43ace9216 5 days ago 133MB
centos latest 300e315adb2f 2 months ago 209MB
[root@localhost home]#
# 3. 启动容器 docker run -d --name nginx01 -p 3344:80 nginx
[root@localhost home]# docker run -d --name nginx01 -p 3344:80 nginx
f649d854e6896b88d8a72afc6a971f6538e74978e0f35eb74934c63bfff6e2d9
[root@localhost home]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
f649d854e689 nginx "/docker-entrypoint.…" 20 seconds ago Up 19 seconds 0.0.0.0:3344->80/tcp nginx01
e2957ebb447c centos "/bin/bash" 26 minutes ago Exited (127) 6 minutes ago quirky_meitner
60a8adaa8f1b centos "/bin/bash" 47 minutes ago Exited (0) 35 minutes ago condescending_joliot
e887b4b948ff centos "/bin/bash" About an hour ago Exited (137) 58 minutes ago goofy_mendel
# 可以看到宿主机3344端口已经映射到docker的80端口,这时在浏览器访问http://192.168.190.129:3344/得到如下结果
Welcome to nginx!
If you see this page, the nginx web server is successfully installed and working. Further configuration is required.
For online documentation and support please refer to nginx.org.
Commercial support is available at nginx.com.
Thank you for using nginx.
# 1. 下载 tomcat镜像
[root@localhost home]# docker pull tomcat
Using default tag: latest
latest: Pulling from library/tomcat
0ecb575e629c: Extracting [========================> ] 25.17MB/50.4MB
7467d1831b69: Download complete
feab2c490a3c: Download complete
f15a0f46f8c3: Downloading [========> ] 8.399MB/51.83MB
26cb1dfcbebb: Waiting
242c5446d23f: Waiting
f22708c7c9c1: Waiting
d8b7e17ca4bc: Waiting
91588c31829d: Waiting
d97abf351b5d: Waiting
# 2. 启动tomcat
[root@localhost home]# docker run -d -p 3345:8080 --name tomcat01 tomcat
405e67657ecd97aa17d1fc23f31a9c1b252a862c9d7523a9b0fced4eb735f985
[root@localhost home]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
405e67657ecd tomcat "catalina.sh run" 11 seconds ago Up 9 seconds 0.0.0.0:3345->8080/tcp tomcat01
f649d854e689 nginx "/docker-entrypoint.…" 21 minutes ago Up 21 minutes 0.0.0.0:3344->80/tcp nginx01
e2957ebb447c centos "/bin/bash" 47 minutes ago Exited (127) 27 minutes ago quirky_meitner
60a8adaa8f1b centos "/bin/bash" About an hour ago Exited (0) 56 minutes ago condescending_joliot
e887b4b948ff centos "/bin/bash" About an hour ago Exited (137) About an hour ago goofy_mendel
[root@localhost home]#
# 直接执行run命令,会自动拉取镜像
[root@localhost home]# docker run -d --name elasticsearch -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" elasticsearch:7.6.2
Unable to find image 'elasticsearch:7.6.2' locally
7.6.2: Pulling from library/elasticsearch
ab5ef0e58194: Downloading [==================> ] 27.93MB/75.78MB
c4d1ca5c8a25: Downloading [========================> ] 15.03MB/31MB
941a3cc8e7b8: Download complete
43ec483d9618: Waiting
c486fd200684: Waiting
1b960df074b2: Waiting
1719d48d6823: Waiting
# 浏览器内访问http://192.168.190.129:9200/,返回如下信息,说明安装成功
{
"name" : "db61203e0963",
"cluster_name" : "docker-cluster",
"cluster_uuid" : "zEjIruAySyiJgJyYl1tA6A",
"version" : {
"number" : "7.6.2",
"build_flavor" : "default",
"build_type" : "docker",
"build_hash" : "ef48eb35cf30adf4db14086e8aabd07ef6fb113f",
"build_date" : "2020-03-26T06:34:37.794943Z",
"build_snapshot" : false,
"lucene_version" : "8.4.0",
"minimum_wire_compatibility_version" : "6.8.0",
"minimum_index_compatibility_version" : "6.0.0-beta1"
},
"tagline" : "You Know, for Search"
}
# 启动es后,发现docker命令变得非常卡顿,用命令docker stats 【CONTAINER ID】可以看到如下信息。说明内存占用比较高,可以在启动es时指定一下占用内存
CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
db61203e0963 elasticsearch 0.30% 609.1MiB / 991.3MiB 61.44% 5.54kB / 4.74kB 2.92GB / 68.3MB 44
# 这样启动之后,内存占用明显下降。
[root@localhost home]# docker run -d --name elasticsearch -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" -e ES_JAVA_OPTS="-Xms64m -Xmx512m" elasticsearch:7.6.2
CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
de8f2f43b5ca elasticsearch 0.93% 398.3MiB / 991.3MiB 40.18% 656B / 0B 303MB / 1.76MB 41
[root@localhost home]# docker run -d -p 8088:9000 --restart=always -v /var/run/docker.sock:/var/run/docker.sock --privileged=true portainer/portainer
Unable to find image 'portainer/portainer:latest' locally
latest: Pulling from portainer/portainer
d1e017099d17: Pulling fs layer
717377b83d5c: Pulling fs layer
镜像是一种轻量级、可执行的独立软件包,用来打包软件运行环境和基于运行环境开发的软件,它包含运行某个软件所需的所有内容,包括代码、运行时文件、库、环境变量和配置文件等。
获取镜像的方式主要有两种:docker pull和自定义镜像。
UnionFS(联合文件系统)
上面例子演示中,每次docker pull都会看到【pulling ** layer】,就是联合文件系统的具体应用。
这是一种分层、轻量级并且高性能的文件系统,它支持对文件系统的修改最为一次提交来层层叠加,同时可以将不同目录挂载到同一个虚拟文件系统下。UnionFS是docker镜像的基础。镜像可以通过分层来进行继承,基于基础镜像(无父镜像的镜像),可以制作各种具体的应用镜像。
就像git一样,任何人都可以通过docker commit来提交自己镜像。
简单来说,就是把宿主机的目录挂载到容器内的某个目录,以实现数据持久化的目的,即使容器被删除,数据仍然可以保留。
以下面的例子做一个说明:
# 可以看到,挂载过程其实很简单,只需要在运行命令的基础上以一个-v参数把宿主机的目录和容器目录关联起来,就可以实现数据同步
[root@localhost ~]# docker run -it -v /home/containerdata:/home centos /bin/bash
[root@5f75528d73b2 /]# ls
bin dev etc home lib lib64 lost+found media mnt opt proc root run sbin srv sys tmp usr var
[root@5f75528d73b2 /]# cd home
[root@5f75528d73b2 home]# ls
[root@5f75528d73b2 home]# vim container-lantian3.txt
bash: vim: command not found
[root@5f75528d73b2 home]# touch container-lantian3.txt
[root@5f75528d73b2 home]# echo "0987654321" > container-lantian3.txt
[root@5f75528d73b2 home]#
# 重开一个窗口,可以看到在宿主机也已经存在上面创建的测试文件
[root@localhost ~]# cd /home
[root@localhost home]# ls
containerdata lantian3.java smbuser test.java
[root@localhost home]# cd containerdata/
[root@localhost containerdata]# ls
container-lantian3.txt
[root@localhost containerdata]# cat container-lantian3.txt
0987654321
[root@localhost containerdata]#
# 另外,通过docker inspect 镜像id命令也可以查看到挂载信息,以下是截取的一部分信息。
"Mounts": [
{
"Type": "bind",
"Source": "/home/containerdata",
"Destination": "/home",
"Mode": "",
"RW": true,
"Propagation": "rprivate"
}
],
# 在宿主机修改该文件,是否能同步到容器内部呢?通过以下输出,可以看到同步是双向的。
[root@localhost containerdata]# echo "12345780" >> container-lantian3.txt
[root@localhost containerdata]# cat container-lantian3.txt
0987654321
12345780
[root@localhost containerdata]#
[root@5f75528d73b2 home]# cat container-lantian3.txt
0987654321
12345780
[root@5f75528d73b2 home]#
# 如果容器停止,数据是否依然存在呢?从以下输出可以看出,即便容器退出,数据仍然保留了下来。
[root@5f75528d73b2 home]# exit
exit
[root@localhost ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
d2545c0b8fd7 portainer/portainer "/portainer" 18 hours ago Up 49 minutes 0.0.0.0:8088->9000/tcp nice_heyrovsky
[root@localhost ~]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
5f75528d73b2 centos "/bin/bash" 12 minutes ago Exited (0) 10 seconds ago nifty_lederberg
d2545c0b8fd7 portainer/portainer "/portainer" 18 hours ago Up 49 minutes 0.0.0.0:8088->9000/tcp nice_heyrovsky
de8f2f43b5ca elasticsearch:7.6.2 "/usr/local/bin/dock…" 18 hours ago Exited (255) 49 minutes ago 0.0.0.0:9200->9200/tcp, 0.0.0.0:9300->9300/tcp elasticsearch
405e67657ecd tomcat "catalina.sh run" 20 hours ago Exited (255) 49 minutes ago 0.0.0.0:3345->8080/tcp tomcat01
f649d854e689 nginx "/docker-entrypoint.…" 20 hours ago Exited (255) 49 minutes ago 0.0.0.0:3344->80/tcp nginx01
e2957ebb447c centos "/bin/bash" 21 hours ago Exited (127) 20 hours ago quirky_meitner
60a8adaa8f1b centos "/bin/bash" 21 hours ago Exited (0) 21 hours ago condescending_joliot
e887b4b948ff centos "/bin/bash" 21 hours ago Exited (137) 21 hours ago goofy_mendel
[root@localhost ~]#
[root@localhost containerdata]# cat container-lantian3.txt
0987654321
12345780
[root@localhost containerdata]#
# 以安装MySQL为例,分别把MySQL的配置文件和数据文件同步到宿主机,加深理解
# -d 表示后台运行
# -p 表示宿主机端口:docker端口的映射
# -v 表示宿主机目录:docker目录映射
# -e 代表修改docker配置
[root@localhost ~]# docker run -d -p 3310:3306 -v /home/mysql/conf:/etc/mysql/conf.d -v /home/mysql/data:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=12345678 --name mysql01 mysql:5.7
Unable to find image 'mysql:5.7' locally
5.7: Pulling from library/mysql
45b42c59be33: Already exists
b4f790bd91da: Pull complete
325ae51788e9: Pull complete
adcb9439d751: Extracting [==================================================>] 1.419MB/1.419MB
174c7fe16c78: Download complete
698058ef136c: Waiting
4690143a669e: Waiting
66676c1ab9b3: Waiting
25ebf78a38b6: Waiting
349a839d5e27: Waiting
40b03e3e5980: Waiting
# 运行成功后,可以看到对应的目录都被关联起来了。
# 需要注意的是,-v 命令可以只写容器目录,而不指定宿主机目录,这样的话,会默认挂载到docker的指定目录,并生成挂载名。
# 此外,还可以这样【/宿主机目录:/docker目录:ro/rw】来指定容器内目录权限,ro代表在容器内该目录只读,rw代表可读可写。
# 用docker volume ls命令查看所有已挂载目录
# 可以用docker volume inspect 【挂载名】命令查看具体挂载信息,可以看到挂载目录就在/var/lib/docker/
[root@localhost home]# docker volume ls
DRIVER VOLUME NAME
local 9d64e933de4f300ab8209a098536e09628646c10331eddaa858df959ee03a9e2
[root@localhost home]# docker volume inspect 9d64e933de4f300ab8209a098536e09628646c10331eddaa858df959ee03a9e2
[
{
"CreatedAt": "2021-02-24T00:47:46+08:00",
"Driver": "local",
"Labels": null,
"Mountpoint": "/var/lib/docker/volumes/9d64e933de4f300ab8209a098536e09628646c10331eddaa858df959ee03a9e2/_data",
"Name": "9d64e933de4f300ab8209a098536e09628646c10331eddaa858df959ee03a9e2",
"Options": null,
"Scope": "local"
}
]
还是以一个例子来体验一下整个简单的流程。
# 在/home目录下新建一个dockerfile目录,方便管理docker file文件,并在其中创建centosDIY文件,写入以下内容:
FROM centos
VOLUME ["volume01","volume02"]
CMD echo "-----end-----"
CMD /bin/bash
# 接着,运行以下命令:
[root@localhost dockerfile]# docker build -f /home/dockerfile/centosDIY -t lantian3/centos:1.0 .
Sending build context to Docker daemon 2.048kB
Step 1/4 : FROM centos
---> 300e315adb2f
Step 2/4 : VOLUME ["volume01","volume02"]
---> Running in 678a16114e82
Removing intermediate container 678a16114e82
---> 201fb9192254
Step 3/4 : CMD echo "-----end-----"
---> Running in 9780f368c50c
Removing intermediate container 9780f368c50c
---> 78fe0c5096e6
Step 4/4 : CMD /bin/bash
---> Running in 360f1f35bfba
Removing intermediate container 360f1f35bfba
---> 72fb6755dc69
Successfully built 72fb6755dc69
Successfully tagged lantian3/centos:1.0
[root@localhost dockerfile]# ls
centosDIY
[root@localhost dockerfile]# docker images
# 此时看到自定义的centos 镜像已经在本地显示出来。
REPOSITORY TAG IMAGE ID CREATED SIZE
lantian3/centos 1.0 72fb6755dc69 7 seconds ago 209MB
nginx latest 35c43ace9216 6 days ago 133MB
tomcat latest bf4709e77b18 2 weeks ago 667MB
mysql 5.7 5f47254ca581 2 weeks ago 449MB
centos latest 300e315adb2f 2 months ago 209MB
portainer/portainer latest 62771b0b9b09 7 months ago 79.1MB
elasticsearch 7.6.2 f29a1ee41030 11 months ago 791MB
[root@localhost dockerfile]#
接下来再看一个例子,来体会一下--volume-from参数可以做的骚操作:
# 用上边自定义的镜像来启动两个centos容器,一个命名为centos001,另一个命名为centos002,后者以前的挂载目录为基础进行挂载。这样一来就可以使实现,两个容器内的数据同步。以此为基础,可以实现MySQL和redis等的分布式数据同步。
# 具体操作如下(第一部分是centos001容器):
[root@localhost ~]# docker run -it --name centos001 lantian3/centos:1.0
[root@275e2d99c108 /]# ls
bin dev etc home lib lib64 lost+found media mnt opt proc root run sbin srv sys tmp usr var volume01 volume02
[root@275e2d99c108 /]# ls
bin dev etc home lib lib64 lost+found media mnt opt proc root run sbin srv sys tmp usr var volume01 volume02
[root@275e2d99c108 /]# cd volume01/
[root@275e2d99c108 volume01]# ls
[root@275e2d99c108 volume01]# ls
lantian3-centos002.txt
[root@275e2d99c108 volume01]# cd ../
[root@275e2d99c108 /]# ls
bin dev etc home lib lib64 lost+found media mnt opt proc root run sbin srv sys tmp usr var volume01 volume02
[root@275e2d99c108 /]# cd volume02
[root@275e2d99c108 volume02]# ls
[root@275e2d99c108 volume02]# touch lantian3-centos001.txt
[root@275e2d99c108 volume02]# ls
lantian3-centos001.txt
# 为了方便观察,再开一个窗口启动centos002
[root@localhost ~]# docker run -it --name centos002 --volumes-from centos001 lantian3/centos:1.0
[root@6438dd2049ce /]# ls
bin dev etc home lib lib64 lost+found media mnt opt proc root run sbin srv sys tmp usr var volume01 volume02
[root@6438dd2049ce /]# cd volume01
[root@6438dd2049ce volume01]# ls
[root@6438dd2049ce volume01]# touch lantian3-centos002.txt
[root@6438dd2049ce volume01]# ls
lantian3-centos002.txt
[root@6438dd2049ce volume01]# ls
lantian3-centos002.txt
[root@6438dd2049ce volume01]# cd ../volume02/
[root@6438dd2049ce volume02]# ls
lantian3-centos001.txt
[root@6438dd2049ce volume02]#
# 可以看到增加了--volumes-from参数后,centos002容器的 volume01 volume02两个目录和centos001容器实现了完全同步。
# 有兴趣可以分别看下docker inspect 【容器id】的目录挂载部分,两个容器中的目录挂载到了完全相同的宿主机目录。
FROM # 指定基础镜像
MAINTAINER # 指定维护者信息
RUN # 指定需要运行的命令
ADD/COPY # 向容器中复制数据
WORKDIR # 设置当前工作目录
VOLUME # 挂载所需目录
EXPOSE # 指定需要访问的端口
CMD # 指定容器启动时需要执行的命令,如果有多个CMD行,后边的会覆盖前边的
ENTRYPOINT # 和CMD类似,不过多行相当于追加,每一行都会执行
下面创建一个实例,体验一下上面的命令:
# 新建dockerfile文件mycentos,并写入如下内容:
[root@localhost dockerfile]# cat mycentos
FROM centos
MAINTAINER lantian3<lantian3@lenovo.com>
ENV MYPATH /usr/local
WORKDIR $MYPATH
RUN mkdir lantian3
RUN mkdir lantian3.another
EXPOSE 80
CMD echo $MYPATH
CMD echo "----end----"
CMD /bin/bash
[root@localhost dockerfile]#
# 以mycentos为dockerfile生成centos:0.1镜像,进入容器,发现多了两个文件夹,说明我们通过RUN关键字指定的命令被执行了
[root@localhost dockerfile]# docker build -f mycentos -t centos:0.1 ./
Sending build context to Docker daemon 3.072kB
Step 1/10 : FROM centos
---> 300e315adb2f
Step 2/10 : MAINTAINER lantian3<lantian3@lenovo.com>
---> Using cache
---> 6756e386bcdd
Step 3/10 : ENV MYPATH /usr/local
---> Using cache
---> 5e41ff2b7417
Step 4/10 : WORKDIR $MYPATH
---> Using cache
---> 94b89b678d88
Step 5/10 : RUN mkdir lantian3
---> Running in f49e4d6cf3cb
Removing intermediate container f49e4d6cf3cb
---> 2dc371ff72fb
Step 6/10 : RUN mkdir lantian3.another
---> Running in d4263008578a
Removing intermediate container d4263008578a
---> 5495be8fec49
Step 7/10 : EXPOSE 80
---> Running in 72d93dba9576
Removing intermediate container 72d93dba9576
---> fda8b00dfa01
Step 8/10 : CMD echo $MYPATH
---> Running in 929fe0482267
Removing intermediate container 929fe0482267
---> 5c646f7ac269
Step 9/10 : CMD echo "----end----"
---> Running in b78098a671d2
Removing intermediate container b78098a671d2
---> 05a2708bdd1b
Step 10/10 : CMD /bin/bash
---> Running in 90b7df5be7e5
Removing intermediate container 90b7df5be7e5
---> a97a1169b8d5
Successfully built a97a1169b8d5
Successfully tagged centos:0.1
[root@localhost dockerfile]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
6438dd2049ce lantian3/centos:1.0 "/bin/sh -c /bin/bash" 22 hours ago Exited (255) 5 hours ago centos002
275e2d99c108 lantian3/centos:1.0 "/bin/sh -c /bin/bash" 22 hours ago Exited (127) 21 hours ago centos001
[root@localhost dockerfile]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
centos 0.1 a97a1169b8d5 24 seconds ago 209MB
lantian3/centos 1.0 72fb6755dc69 2 days ago 209MB
nginx latest 35c43ace9216 8 days ago 133MB
tomcat latest bf4709e77b18 2 weeks ago 667MB
mysql 5.7 5f47254ca581 2 weeks ago 449MB
centos latest 300e315adb2f 2 months ago 209MB
portainer/portainer latest 62771b0b9b09 7 months ago 79.1MB
elasticsearch 7.6.2 f29a1ee41030 11 months ago 791MB
[root@localhost dockerfile]# docker run -it --name mycentos centos:0.1
[root@a74c0b16631d local]# ls
bin etc games include lantian3 lantian3.another lib lib64 libexec sbin share src
[root@a74c0b16631d local]#
# docker history 【镜像id】可以查看镜像创建历史信息
[root@localhost dockerfile]# docker history a97a1169b8d5
IMAGE CREATED CREATED BY SIZE COMMENT
a97a1169b8d5 6 minutes ago /bin/sh -c #(nop) CMD ["/bin/sh" "-c" "/bin… 0B
05a2708bdd1b 6 minutes ago /bin/sh -c #(nop) CMD ["/bin/sh" "-c" "echo… 0B
5c646f7ac269 6 minutes ago /bin/sh -c #(nop) CMD ["/bin/sh" "-c" "echo… 0B
fda8b00dfa01 6 minutes ago /bin/sh -c #(nop) EXPOSE 80 0B
5495be8fec49 6 minutes ago /bin/sh -c mkdir lantian3.another 0B
2dc371ff72fb 6 minutes ago /bin/sh -c mkdir lantian3 0B
94b89b678d88 14 minutes ago /bin/sh -c #(nop) WORKDIR /usr/local 0B
5e41ff2b7417 14 minutes ago /bin/sh -c #(nop) ENV MYPATH=/usr/local 0B
6756e386bcdd 14 minutes ago /bin/sh -c #(nop) MAINTAINER lantian3<lanti… 0B
300e315adb2f 2 months ago /bin/sh -c #(nop) CMD ["/bin/bash"] 0B
<missing> 2 months ago /bin/sh -c #(nop) LABEL org.label-schema.sc… 0B
<missing> 2 months ago /bin/sh -c #(nop) ADD file:bd7a2aed6ede423b7… 209MB
[root@localhost dockerfile]#
# 在Linux执行ip addr命令,可以看到,除了本地网卡lo和默认网卡eth0,还多了一个docker0,这个就是docker的网卡
[root@localhost dockerfile]# ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UNKNOWN group default qlen 1000
link/ether 00:0c:29:45:bc:62 brd ff:ff:ff:ff:ff:ff
inet 192.168.190.129/24 brd 192.168.190.255 scope global noprefixroute dynamic ens33
valid_lft 1713sec preferred_lft 1713sec
inet6 fe80::94e9:4b31:f8db:88a0/64 scope link noprefixroute
valid_lft forever preferred_lft forever
3: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default
link/ether 02:42:77:84:78:ce brd ff:ff:ff:ff:ff:ff
inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0
valid_lft forever preferred_lft forever
inet6 fe80::42:77ff:fe84:78ce/64 scope link
valid_lft forever preferred_lft foreve
# 而进入docker 容器后,运行ip addr命令,得到的结果如下,我们用cnetos来举例:
[root@localhost dockerfile]# docker run -it centos:latest ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
34: eth0@if35: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
link/ether 02:42:ac:11:00:02 brd ff:ff:ff:ff:ff:ff link-netnsid 0
inet 172.17.0.2/16 brd 172.17.255.255 scope global eth0
valid_lft forever preferred_lft forever
[root@localhost dockerfile]#
# 这说明,宿主机和容器是通过docker0来通信的,docker0的作用类似路由器。