Docker的基础用法
Docker
docker中的容器:
- lxc --> libcontainer --> runC
OCI&OCF
OCI
Open Container-initiative
- 由Linux基金会主导于2015年6月创立
- 旨在围绕容器格式和运行时制定一个开放的工业化标准
- contains two specifications(包含两个规格)
- the Runtime Specification(runtime-spec)(运行时规范)
- the Image Specification(image-spec)(形象规范)
OCF
Open Container Format(打开容器格式)
runC is a CLI tool for spawning and running containers according to the OCI specification(runC是一个CLI工具,用于根据OCI规范生成和运行容器)
- Containers are started as a child process of runC and can be embedded into various other systems without having to run a daemon(容器作为runC的子进程启动,可以嵌入到各种其他系统中,而不需要运行守护进程)
- runC is built on libcontainer, the same container technology powering millions of Docker Engine installations(runC是基于libcontainer构建的,同样的容器技术为数百万的Docker引擎安装提供了动力)
docker提供了一个专门容纳容器镜像的站点:https://hub.docker.com
Docker架构
Docker镜像与镜像仓库
镜像仓库名字为registry,在docker中仓库的名字是以应用的名称取名的。
镜像是静态的,而容器是动态的,容器有其生命周期,镜像与容器的关系类似于程序与进程的关系。镜像类似于文件系统中的程序文件,而容器则类似于将一个程序运行起来的状态,也即进程。所以容器是可以删除的,容器被删除后其镜像是不会被删除的。
docker对象
When you use docker, you are creating and using images, containers, networks, volumes, pluginns, and other objects.(当您使用 docker 时,您正在创建和使用镜像、容器、网络、卷、插件和其他对象。)
-
IMAGES(镜像)
- An image is a read-only template with instructions for creating a docker container.(镜像是一个只读模板,其中包含创建 docker 容器的说明。)
- Often, an image is based on another image, with some additional customization.(通常,一个镜像基于另一个镜像,并带有一些额外的自定义。)
- You might create your own images or you might only use those created by others and published in a registry.(您可以创建自己的镜像,也可以使用其他人创建并在仓库中发布的镜像。)
-
CONTAINERS(容器)
- A conntainer is a runnable instance of an image.(容器是镜像的可运行实例。)
- You can create, run, stop, move, or delete a container using the docker API or CLI.(您可以使用 docker API 或 CLI 创建、运行、停止、移动或删除容器。)
- You can connect a container to one or more networks, attach storage to it, or even create a new image based on its current state.(您可以将容器连接到一个或多个网络,为其附加存储,甚至可以根据其当前状态创建新镜像。)
安装和使用Docker
安装Docker
[root@localhost ~]# cd /etc/yum.repos.d/
[root@localhost yum.repos.d]# curl -o docker-ce.repo https://mirrors.tuna.tsinghua.edu.cn/docker-ce/linux/centos/docker-ce.repo
[root@localhost yum.repos.d]# sed -i 's@https://download.docker.com@https://mirrors.tuna.tsinghua.edu.cn/docker-ce@g' docker-ce.repo
[root@localhost yum.repos.d]# yum clean all
[root@localhost ~]# yum -y install docker-ce
docker加速
docker-ce的配置文件是/etc/docker/daemon.json,此文件默认不存在,需要我们手动创建并进行配置,而docker的加速就是通过配置此文件来实现的。
docker的加速有多种方式:
- docker cn
- 中国科技大学加速器
- 阿里云加速器(需要通过阿里云开发者平台注册帐号,免费使用个人私有的加速器)
登录阿里云账号后点击控制台
点击左上角按钮
找到容器镜像服务
点击镜像工具——>镜像加速器
[root@localhost ~]# mkdir -p /etc/docker
[root@localhost ~]# cat /etc/docker/daemon.json
{
"registry-mirrors": ["https://7z2g0ixw.mirror.aliyuncs.com"]
}
[root@localhost ~]# systemctl enable --now docker
Created symlink /etc/systemd/system/multi-user.target.wants/docker.service → /usr/lib/systemd/system/docker.service.
[root@localhost ~]# docker info
......
Insecure Registries:
127.0.0.0/8
Registry Mirrors:
https://7z2g0ixw.mirror.aliyuncs.com/
Live Restore Enabled: false
Docker常用命令
命令 | 功能 |
---|---|
docker search | Search the Docker Hub for images |
docker pull | Pull an image or a repository from a registry |
docker images | List images |
docker create | Create a new conntainer |
docker start | Start one or more stopped containers |
docker run | Run a command in a new container |
docker attach | Attach to a runninng container |
docker ps | List containers |
docker logs | Fetch the logs of a container |
docker restart | Restart a container |
docker stop | Stop one or more running containers |
docker kill | Kill one or more running containers |
docker rm | Remove onne or more containers |
docker exec | Run a command in a running container |
docker info | Display system-wide information |
docker inspect | Return low-level information on Docker objects |
docker
查看Docker基本信息、命令列表
[root@localhost ~]# docker
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.6.3-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
scan* Docker Scan (Docker Inc., v0.9.0)
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/
docker info
查看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.6.3-docker)
scan: Docker Scan (Docker Inc., v0.9.0)
Server:
Containers: 0
Running: 0
Paused: 0
Stopped: 0
Images: 0
Server Version: 20.10.11
Storage Driver: overlay2
Backing Filesystem: xfs
Supports d_type: true
......
docker version
查看Docker版本信息
[root@localhost ~]# docker version
Client: Docker Engine - Community
Version: 20.10.11
API version: 1.41
Go version: go1.16.9
Git commit: dea9396
Built: Thu Nov 18 00:36:58 2021
OS/Arch: linux/amd64
Context: default
Experimental: true
Server: Docker Engine - Community
Engine:
Version: 20.10.11
API version: 1.41 (minimum version 1.12)
Go version: go1.16.9
Git commit: 847da18
Built: Thu Nov 18 00:35:20 2021
OS/Arch: linux/amd64
Experimental: false
containerd:
Version: 1.4.12
GitCommit: 7b11cfaabd73bb80907dd23182b9347b4245eb5d
runc:
Version: 1.0.2
GitCommit: v1.0.2-0-g52b36a2
docker-init:
Version: 0.19.0
GitCommit: de40ad0
docker search
搜索镜像 镜像仓库.
[root@localhost ~]# docker search nginx
NAME DESCRIPTION STARS OFFICIAL AUTOMATED
nginx Official build of Nginx. 15899 [OK]
jwilder/nginx-proxy Automated Nginx reverse proxy for docker con… 2098 [OK]
richarvey/nginx-php-fpm Container running Nginx + PHP-FPM capable of… 819 [OK]
jc21/nginx-proxy-manager Docker container for managing Nginx proxy ho… 285
linuxserver/nginx An Nginx container, brought to you by LinuxS… 160
tiangolo/nginx-rtmp Docker image with Nginx using the nginx-rtmp… 146 [OK]
......
NAME //镜像仓库源的名称
DESCRIPTION //表示该镜像的功能
STARS //表示下载热度
OFFICIAL //是否docker官方发布
AUTOMATED //自动构建
docker pull
拉取镜像
[root@localhost ~]# docker pull nginx
Using default tag: latest
latest: Pulling from library/nginx
eff15d958d66: Pull complete
1e5351450a59: Pull complete
2df63e6ce2be: Pull complete
9171c7ae368c: Pull complete
020f975acd28: Pull complete
266f639b35ad: Pull complete
Digest: sha256:097c3a0913d7e3a5b01b6c685a60c03632fc7a2b50bc8e35bcaa3691d788226e
Status: Downloaded newer image for nginx:latest
docker.io/library/nginx:latest
docker images
查看已安装的镜像
[root@localhost ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
nginx latest ea335eea17ab 2 weeks ago 141MB
docker images [镜像名] //查看本地主机上的所有/指定镜像
选项:
-a //列出本地所有的镜像;
--digests //显示镜像的摘要信息;
-q //只显示镜像ID。
REPOSITORY //镜像的仓库源
TAG //镜像标签
IMAGE ID //镜像ID
CREATED //镜像创建时间
SIZE //镜像大小
docker run
运行一个容器,自动拉取镜像、自动创建容器、自动运行
[root@localhost ~]# docker run -itd --name nginx1 nginx
6d4f80e6f2cb0b1526e84df8273f42e91a2030fea703a194137581135803800b
docker run //从镜像运行一个容器
选项:
--name //指定容器的名称,如果不指定随机给容器生成一个名称
-it //为容器分配一个始终运行的伪终端,需要指定shell;-i保持运行状态,-t是分配伪终端,不建议run时使用
-d //容器以守护进程的方式运行
-p 宿主机端口:容器端口 //将宿主机端口映射给容器端口
-v 宿主机目录:容器目录 //将宿主机目录挂载到容器中;直接写容器目录省略宿主机目录,将在宿主机自动创建一个目录挂载到容器中
-e //启动容器时传递环境及其值
--rm //容器退出时删除容器
--cpuset-cpus CPU序号 //容器能够使用哪些物理cpu
--cpu-shares 数值 //CPU共享权值(相对权重)
--memory 数值 //容器内存限制,单位b,k,m,g
--memory-swap 数值 //容器内存+交换分区大小,不能小-m的值
--restart 策略 //指定容器停止后的重启策略
no //容器退出时不重启
on-failure //容器故障退出(返回值非零)时重启
always //容器退出时总是重启
--network 网络名称 //容器网络设置
bridge //使用桥接模式
host //容器使用主机的网络
container:NAME_or_ID //使用其他容器的网路,共享IP和PORT等网络资源
none //容器使用自己的网络(类似bridge);但是不进行配置,如分配veth pair 和网桥连接,配置IP等
--link 容器名称 //指定容器间的关联,可以和指定容器进行通信
docker create
创建一个新容器,不运行
[root@localhost ~]# docker create --name nginx2 nginx
49d3c71c03076c621024cb0cd831d72cc86ea311e29ad56176423d74af241703
docker ps
查看容器运行状态
[root@localhost ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
6d4f80e6f2cb nginx "/docker-entrypoint.…" 3 minutes ago Up 3 minutes 80/tcp nginx1
[root@localhost ~]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
49d3c71c0307 nginx "/docker-entrypoint.…" 2 minutes ago Created nginx2
6d4f80e6f2cb nginx "/docker-entrypoint.…" 3 minutes ago Up 3 minutes 80/tcp nginx1
docker ps //查看容器运行状态
选项:
-a //显示所有的容器,包括未运行的
-q //只显示容器id
-l //显示最近创建的容器。
-f "筛选条件" //根据条件过滤显示的内容
CONTAINER ID //容器 ID
IMAGE //使用的镜像
COMMAND //启动容器时运行的命令
CREATED //容器的创建时间
STATUS //容器状态
状态有7种:
created(已创建)
restarting(重启中)
running(运行中)
removing(迁移中)
paused(暂停)
exited(停止)
dead(死亡)
PORTS //容器的端口信息和使用的连接类型(tcp\udp)。
NAMES //容器名称
docker start
开启一个或多个已经关闭的容器
[root@localhost ~]# docker start 49d3c71c0307
49d3c71c0307
[root@localhost ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
49d3c71c0307 nginx "/docker-entrypoint.…" 6 minutes ago Up 9 seconds 80/tcp nginx2
6d4f80e6f2cb nginx "/docker-entrypoint.…" 7 minutes ago Up 7 minutes 80/tcp nginx1
docker stop
停止容器
[root@localhost ~]# docker stop 49d3c71c0307
49d3c71c0307
[root@localhost ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
6d4f80e6f2cb nginx "/docker-entrypoint.…" 8 minutes ago Up 8 minutes 80/tcp nginx1
docker kill
杀掉容器
[root@localhost ~]# docker kill 6d4f80e6f2cb
6d4f80e6f2cb
[root@localhost ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
docker attach
连接到正在运行的容器上
[root@localhost ~]# docker attach nginx2
[root@49d3c71c0307 /]#
docker exec
进入容器
[root@localhost ~]# docker exec -it nginx1 /bin/bash
root@6d4f80e6f2cb:/# ls
bin dev docker-entrypoint.sh home lib64 mnt proc run srv tmp var
boot docker-entrypoint.d etc lib media opt root sbin sys usr
root@6d4f80e6f2cb:/# exit
exit
docker exec 容器名 执行命令 //不进入容器执行容器中的命令
选项:
-d //后台执行,不显示结果
-it //为容器分配一个始终运行的伪终端,需要指定shell;-i保持运行状态,-t是分配伪终端
docker logs
查看容器日志
[root@localhost ~]# docker logs nginx1
/docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
/docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
/docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
10-listen-on-ipv6-by-default.sh: info: Getting the checksum of /etc/nginx/conf.d/default.conf
10-listen-on-ipv6-by-default.sh: info: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf
/docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
/docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh
......
docker logs 容器名 //获取容器的日志信息
选项:
-f //跟随打印最新的日志追加在最后面
-t //显示日志打印的时间戳
--tail 数量 //只显示最新的指定数量的几条日志信息
docker rm
删除容器
[root@localhost ~]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
abed33842626 nginx "/docker-entrypoint.…" 7 seconds ago Created nginx3
49d3c71c0307 nginx "/docker-entrypoint.…" 19 minutes ago Exited (0) 4 minutes ago nginx2
6d4f80e6f2cb nginx "/docker-entrypoint.…" 20 minutes ago Up 3 minutes 80/tcp nginx1
[root@localhost ~]# docker rm abed33842626
abed33842626
[root@localhost ~]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
49d3c71c0307 nginx "/docker-entrypoint.…" 20 minutes ago Exited (0) 5 minutes ago nginx2
6d4f80e6f2cb nginx "/docker-entrypoint.…" 21 minutes ago Up 3 minutes 80/tcp nginx1
docker rm 容器名 //删除容器,无法删除运行状态下的容器
选项:
-f //强制,可以删除运行状态下的容器
//批量删除所有容器
[root@localhost ~]# docker rm `docker ps -qa`
49d3c71c0307
6d4f80e6f2cb
[root@localhost ~]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
docker rmi
删除镜像
[root@localhost ~]# docker rmi -f nginx
Untagged: nginx:latest
Untagged: nginx@sha256:097c3a0913d7e3a5b01b6c685a60c03632fc7a2b50bc8e35bcaa3691d788226e
[root@localhost ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
<none> <none> ea335eea17ab 2 weeks ago 141MB
docker rmi 镜像名:标签 //删除镜像
选项:
-f //强制删除
docker inspect
用于以JSON格式显示容器与镜像的详细信息
[root@localhost ~]# docker inspect nginx1
[
{
"Id": "9c95e5cb911e38b4c7c77e95e78e1e894777f0d38cfe3ea15d38b7ab081173d5",
"Created": "2021-12-01T11:04:47.042370965Z",
"Path": "/docker-entrypoint.sh",
"Args": [
"nginx",
"-g",
"daemon off;"
],
"State": {
"Status": "running",
"Running": true,
"Paused": false,
"Restarting": false,
"OOMKilled": false,
"Dead": false,
"Pid": 12393,
"ExitCode": 0,
"Error": "",
"StartedAt": "2021-12-01T11:04:47.713791436Z",
"FinishedAt": "0001-01-01T00:00:00Z"
},
"Image": "sha256:ea335eea17ab984571cd4a3bcf90a0413773b559c75ef4cda07d0ce952b00291",
"ResolvConfPath": "/var/lib/docker/containers/9c95e5cb911e38b4c7c77e95e78e1e894777f0d38cfe3ea15d38b7ab081173d5/resolv.conf",
"HostnamePath": "/var/lib/docker/containers/9c95e5cb911e38b4c7c77e95e78e1e894777f0d38cfe3ea15d38b7ab081173d5/hostname",
"HostsPath": "/var/lib/docker/containers/9c95e5cb911e38b4c7c77e95e78e1e894777f0d38cfe3ea15d38b7ab081173d5/hosts",
"LogPath": "/var/lib/docker/containers/9c95e5cb911e38b4c7c77e95e78e1e894777f0d38cfe3ea15d38b7ab081173d5/9c95e5cb911e38b4c7c77e95e78e1e894777f0d38cfe3ea15d38b7ab081173d5-json.log",
"Name": "/nginx1",
"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,
......