Docker基础

Docker Use

Posted by BlueFat on Saturday, October 24, 2020

查看Docker版本

[root@k8s-master01 ~]# docker version
Client: Docker Engine - Community
 Version:           20.10.7
 API version:       1.40
 Go version:        go1.13.15
 Git commit:        f0df350
 Built:             Wed Jun  2 11:58:10 2021
 OS/Arch:           linux/amd64
 Context:           default
 Experimental:      true

Server: Docker Engine - Community
 Engine:
  Version:          19.03.15
  API version:      1.40 (minimum version 1.12)
  Go version:       go1.13.15
  Git commit:       99e3ed8919
  Built:            Sat Jan 30 03:16:33 2021
  OS/Arch:          linux/amd64
  Experimental:     false
 containerd:
  Version:          1.4.6
  GitCommit:        d71fcd7d8303cbf684402823e425e9dd2e99285d
 runc:
  Version:          1.0.0-rc95
  GitCommit:        b9ee9c6314599f1b4a7f497e1f1f856fe433d3b7
 docker-init:
  Version:          0.18.0
  GitCommit:        fec3683

Docker详细信息

[root@k8s-master01 ~]# 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)
  scan: Docker Scan (Docker Inc., v0.8.0)

Server:
 Containers: 6
  Running: 4
  Paused: 0
  Stopped: 2
 Images: 9
 Server Version: 19.03.15
 Storage Driver: overlay2 # 官方推荐的存储驱动,要求文件系统是xfs,必须支持d_type(目录条目类型,内核上的一个数据,安装系统的时候必须把ftype设置为1,不然的话很影响docker的性能),目前流行的Storage Driver有aufs(ubuntu支持)、overlay、brtfs
  Backing Filesystem: xfs
  Supports d_type: true
  Native Overlay Diff: true
 Logging Driver: json-file # docker日志的存储类型,json-file会存储在本地,目录在Docker Root Dir
 Cgroup Driver: systemd
 Plugins:
  Volume: local
  Network: bridge host ipvlan macvlan null overlay
  Log: awslogs fluentd gcplogs gelf journald json-file local logentries splunk syslog
 Swarm: inactive # 容器编排工具,inactive未启动
 Runtimes: runc
 Default Runtime: runc # docker运行的核心
 Init Binary: docker-init
 containerd version: d71fcd7d8303cbf684402823e425e9dd2e99285d
 runc version: b9ee9c6314599f1b4a7f497e1f1f856fe433d3b7
 init version: fec3683
 Security Options:
  seccomp
   Profile: default
 Kernel Version: 4.19.12-1.el7.elrepo.x86_64 # 内核版本低于3.18不能使用overlay2存储驱动,linux3.18才加入的
 Operating System: CentOS Linux 7 (Core)
 OSType: linux
 Architecture: x86_64
 CPUs: 2
 Total Memory: 1.923GiB
 Name: k8s-master01
 ID: PYSL:2OAV:4C7N:WAI3:7G3J:IBR5:6BXI:7OEG:YNCL:6RAR:3CTF:CTDD
 Docker Root Dir: /var/lib/docker # 这个目录可以修改,生产环境推荐使用ssd硬盘存储,挂载在该目录,可以提高docker的性能,条件不足的情况下,最好使用一个单独的磁盘进行挂载,不要和宿主机用同一个磁盘
 Debug Mode: false
 Registry: https://index.docker.io/v1/ # 官方镜像仓库,访问较慢,可以修改为自己的镜像仓库
 Labels:
 Experimental: false
 Insecure Registries: # 如果使用的非官方镜像仓库地址不是https,需要把链接加入到此非安全列表
  127.0.0.0/8
 Live Restore Enabled: false # 生产环境中需要打开,重启docker进程不会重启正在运行的容器,如果容器没有设置自动重启就会被关闭,不会重启

查看d_type信息(ftype=1说明系统支持d_type)

[root@k8s-master01 ~]# xfs_info /
meta-data=/dev/mapper/centos-root isize=512    agcount=4, agsize=1113856 blks
         =                       sectsz=512   attr=2, projid32bit=1
         =                       crc=1        finobt=0 spinodes=0
data     =                       bsize=4096   blocks=4455424, imaxpct=25
         =                       sunit=0      swidth=0 blks
naming   =version 2              bsize=4096   ascii-ci=0 ftype=1
log      =internal               bsize=4096   blocks=2560, version=2
         =                       sectsz=512   sunit=0 blks, lazy-count=1
realtime =none                   extsz=4096   blocks=0, rtextents=0

进入Docker Root Dir,进入任何一个容器目录既可查看对应容器的日志,每次docker重启的时候日志就会被清除

[root@k8s-master01 ~]# cd /var/lib/docker/containers/

[root@k8s-master01 containers]# ll
total 0
drwx-----x 4 root root 165 Jul 12 10:54 10b58a593a5f417d466fbb2eba54c6ac0e8322a3712cbc6eb46f9cae5b48e4d8

[root@k8s-master01 10b58a593a5f417d466fbb2eba54c6ac0e8322a3712cbc6eb46f9cae5b48e4d8]# ll
total 16
-rw-r----- 1 root root 4042 Jul 12 10:53 10b58a593a5f417d466fbb2eba54c6ac0e8322a3712cbc6eb46f9cae5b48e4d8-json.log

Insecure Registries目录

[root@k8s-master01 ~]# vim /etc/docker/daemon.json

{
    "registry-mirrors": [
    "https://registry.docker-cn.com",
    "http://hub-mirror.c.163.com",
    "https://docker.mirrors.ustc.edu.cn"
  ],
 "exec-opts": ["native.cgroupdriver=systemd"],
 "max-concurrent-downloads": 10, # 并发下载的线程数
 "max-concurrent-uploads": 5, # 并发上传的线程数
 "log-opts": {
     "max-size": "300m", # 限制日志文件最大容量,超过则分割
     "max-file": "2" # 日志保存最大数量
 },
 "live-restore": true # 更改docker配置之后需要重启docker才能生效,这个参数可以使得重启docker不影响正在运行的容器进程
}

搜索镜像

[root@k8s-master01 ~]# docker search centos
NAME                              DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
centos                            The official build of CentOS.                   6631      [OK]       
ansible/centos7-ansible           Ansible on Centos7                              134                  [OK]
consol/centos-xfce-vnc            Centos container with "headless" VNC session…   129                  [OK]
jdeathe/centos-ssh                OpenSSH / Supervisor / EPEL/IUS/SCL Repos -118                  [OK]
centos/systemd                    systemd enabled base container.                 100                  [OK]
centos/mysql-57-centos7           MySQL 5.7 SQL database server                   88                   
imagine10255/centos6-lnmp-php56   centos6-lnmp-php56                              58                   [OK]
tutum/centos                      Simple CentOS docker image with SSH access      48                   
centos/postgresql-96-centos7      PostgreSQL is an advanced Object-Relational …   45                   
jdeathe/centos-ssh-apache-php     Apache PHP - CentOS.                            31                   [OK]
kinogmt/centos-ssh                CentOS with SSH                                 29                   [OK]
guyton/centos6                    From official centos6 container with full up…   10                   [OK]
nathonfowlie/centos-jre           Latest CentOS image with the JRE pre-install…   8                    [OK]
centos/tools                      Docker image that has systems administration…   7                    [OK]
drecom/centos-ruby                centos ruby                                     6                    [OK]
mamohr/centos-java                Oracle Java 8 Docker image based on Centos 7    3                    [OK]
darksheer/centos                  Base Centos Image -- Updated hourly             3                    [OK]
miko2u/centos6                    CentOS6 日本語環境                                   2                    [OK]
amd64/centos                      The official build of CentOS.                   2                    
dokken/centos-7                   CentOS 7 image for kitchen-dokken               2                    
indigo/centos-maven               Vanilla CentOS 7 with Oracle Java Developmen…   2                    [OK]
mcnaughton/centos-base            centos base image                               1                    [OK]
blacklabelops/centos              CentOS Base Image! Built and Updates Daily!     1                    [OK]
starlabio/centos-native-build     Our CentOS image for native builds              0                    [OK]
smartentry/centos                 centos with smartentry                          0                    [OK]

OFFICIAL的值是ok代表官方容器,一般都是使用官方的

拉取镜像

alpine可以作为基础镜像,拉取镜像的时候如果本地已经存在,则不会重复拉取

可以通过官网搜索镜像:https://hub.docker.com/

拉取镜像,如果本地已有该镜像,则不会重复拉取

[root@k8s-master01 ~]# docker pull alpine:latest
latest: Pulling from library/alpine
5843afab3874: Pull complete 
Digest: sha256:234cb88d3020898631af0ccbbcca9a66ae7306ecd30c9720690858c1b007d2a0
Status: Downloaded newer image for alpine:latest
docker.io/library/alpine:latest

默认拉取官方镜像,如果需要拉取指定镜像,需要添加地址,版本号

推送镜像

查看镜像

[root@k8s-master01 ~]# docker images
REPOSITORY                                                        TAG       IMAGE ID       CREATED         SIZE
nginx                                                             latest    4cdc5dd7eaad   7 days ago      133MB
kubernetesui/dashboard                                            v2.3.1    e1482a24335a   3 weeks ago     220MB
alpine                                                            latest    d4ff818577bc   4 weeks ago     5.6MB
registry.cn-beijing.aliyuncs.com/dotbalo/node                     v3.15.3   d45bf977dfbf   10 months ago   262MB
registry.cn-beijing.aliyuncs.com/dotbalo/pod2daemon-flexvol       v3.15.3   963564fb95ed   10 months ago   22.8MB
registry.cn-beijing.aliyuncs.com/dotbalo/cni                      v3.15.3   ca5564c06ea0   10 months ago   110MB
kubernetesui/dashboard                                            v2.0.3    503bc4b7440b   12 months ago   225MB
registry.cn-beijing.aliyuncs.com/dotbalo/coredns                  1.7.0     bfe3a36ebd25   13 months ago   45.2MB
registry.cn-beijing.aliyuncs.com/dotbalo/metrics-scraper          v1.0.4    86262685d9ab   15 months ago   36.9MB
registry.cn-hangzhou.aliyuncs.com/google_containers/pause-amd64   3.2       80d28bedfe5d   17 months ago   683kB

镜像打标签到自己的镜像仓库

[root@k8s-master01 ~]# docker tag registry.cn-beijing.aliyuncs.com/dotbalo/pod2daemon-flexvol:v3.15.3 mingsonzheng/pod2daemon-flexvol:v3.15.3

登录远程镜像仓库

[root@k8s-master01 ~]# docker login
Login with your Docker ID to push and pull images from Docker Hub. If you don't have a Docker ID, head over to https://hub.docker.com to create one.
Username: mingsonzheng
Password: 
WARNING! Your password will be stored unencrypted in /root/.docker/config.json.
Configure a credential helper to remove this warning. See
https://docs.docker.com/engine/reference/commandline/login/#credentials-store

Login Succeeded

登录到指定仓库

docker login xxx.com

推送镜像

[root@k8s-master01 ~]# docker push mingsonzheng/pod2daemon-flexvol:v3.15.3
The push refers to repository [docker.io/mingsonzheng/pod2daemon-flexvol]
f0e55d2e215d: Pushed 
7b2f85666007: Pushed 
752045c6df15: Pushed 
ca07dc9dd06e: Pushed 
1d0352c1c217: Pushed 
540c65dd0455: Pushed 
48855504bcc3: Pushed 
v3.15.3: digest: sha256:6bd1246d0ea1e573a6a050902995b1666ec0852339e5bda3051f583540361b55 size: 1788

启动镜像

  • 前台启动
  • 后台启动

前台启动,如果本地没有镜像会先拉取

[root@k8s-master01 ~]# docker run -ti centos:8 bash
Unable to find image 'centos:8' locally
8: Pulling from library/centos
7a0437f04f83: Pull complete 
Digest: sha256:5528e8b1b1719d34604c87e11dcd1c0a20bedf46e83b5632cdeac91b8c04efc1
Status: Downloaded newer image for centos:8
[root@a4cb8f5d6bd5 /]# 

后台启动

[root@k8s-master01 ~]# docker run -d centos:8 bash
617a1213ae5ce5c4bed0716fd5b3212b25ed7bcc2099ba329db54cccd3c0b8d5
[root@k8s-master01 ~]# 

查看容器

查看正在运行的容器

[root@k8s-master01 ~]# docker ps
CONTAINER ID   IMAGE                                                                 COMMAND                  CREATED              STATUS                          PORTS     NAMES
617a1213ae5c   centos:8                                                              "bash"                   About a minute ago   Exited (0) About a minute ago             vigilant_boyd
04b21dff00f5   centos:8                                                              "bash"                   2 minutes ago        Exited (0) 2 minutes ago                  objective_satoshi
a4cb8f5d6bd5   centos:8                                                              "bash"                   5 minutes ago        Exited (127) 2 minutes ago                reverent_elgamal

查看所有状态的容器

[root@k8s-master01 ~]# docker ps -a
CONTAINER ID   IMAGE                                                                 COMMAND                  CREATED          STATUS                        PORTS     NAMES
1d906297395d   centos:8                                                              "bash"                   2 minutes ago    Exited (0) 2 minutes ago                wonderful_hermann
617a1213ae5c   centos:8                                                              "bash"                   22 minutes ago   Exited (0) 22 minutes ago               vigilant_boyd
04b21dff00f5   centos:8                                                              "bash"                   22 minutes ago   Exited (0) 22 minutes ago               objective_satoshi
a4cb8f5d6bd5   centos:8                                                              "bash"                   26 minutes ago   Exited (127) 22 minutes ago             reverent_elgamal
a3db403fd0be   kubernetesui/dashboard                                                "/dashboard --insecu…"   46 hours ago     Up 46 hours                             k8s_kubernetes-dashboard_kubernetes-dashboard-67484c44f6-brz2z_kubernetes-dashboard_bb016e8e-a4b1-48e6-912c-022addfb72bf_0
8cd76e9123b3   registry.cn-hangzhou.aliyuncs.com/google_containers/pause-amd64:3.2   "/pause"                 46 hours ago     Up 46 hours                             k8s_POD_kubernetes-dashboard-67484c44f6-brz2z_kubernetes-dashboard_bb016e8e-a4b1-48e6-912c-022addfb72bf_0
dbec965d88da   registry.cn-beijing.aliyuncs.com/dotbalo/node                         "start_runit"            2 days ago       Up 2 days                               k8s_calico-node_calico-node-gn8ws_kube-system_16eeb29c-3383-4e62-b84c-40bf3dae7d07_0
e9869813fc1b   registry.cn-beijing.aliyuncs.com/dotbalo/pod2daemon-flexvol           "/usr/local/bin/flex…"   2 days ago       Exited (0) 2 days ago                   k8s_flexvol-driver_calico-node-gn8ws_kube-system_16eeb29c-3383-4e62-b84c-40bf3dae7d07_0
10b58a593a5f   registry.cn-beijing.aliyuncs.com/dotbalo/cni                          "/install-cni.sh"        2 days ago       Exited (0) 2 days ago                   k8s_install-cni_calico-node-gn8ws_kube-system_16eeb29c-3383-4e62-b84c-40bf3dae7d07_0
610909969be1   registry.cn-hangzhou.aliyuncs.com/google_containers/pause-amd64:3.2   "/pause"                 2 days ago       Up 2 days                               k8s_POD_calico-node-gn8ws_kube-system_16eeb29c-3383-4e62-b84c-40bf3dae7d07_0

查看正在运行的容器的id

[root@k8s-master01 ~]# docker ps -q
a3db403fd0be
8cd76e9123b3
dbec965d88da
610909969be1

查看所有的容器的id

[root@k8s-master01 ~]# docker ps -aq
1d906297395d
617a1213ae5c
04b21dff00f5
a4cb8f5d6bd5
a3db403fd0be
8cd76e9123b3
dbec965d88da
e9869813fc1b
10b58a593a5f
610909969be1

查看日志

[root@k8s-master01 ~]# docker logs -f a3db403fd0be

对应日志路径

/var/lib/docker/containers/a3db403fd0be5eacb8aa1769cc8d215da93eb74da84262aa1aac11551c37a84d

进入容器

启动容器

[root@k8s-master01 ~]# docker run -ti nginx:1.14.2 sh
# 

Xshell 7新建一个链接到服务器

查看运行中的容器

[root@k8s-master01 ~]# docker ps
CONTAINER ID   IMAGE                                                                 COMMAND                  CREATED          STATUS          PORTS     NAMES
2ef850f11136   nginx:1.14.2                                                          "sh"                     29 seconds ago   Up 28 seconds   80/tcp    funny_leavitt
a3db403fd0be   kubernetesui/dashboard                                                "/dashboard --insecu…"   2 days ago       Up 2 days                 k8s_kubernetes-dashboard_kubernetes-dashboard-67484c44f6-brz2z_kubernetes-dashboard_bb016e8e-a4b1-48e6-912c-022addfb72bf_0
8cd76e9123b3   registry.cn-hangzhou.aliyuncs.com/google_containers/pause-amd64:3.2   "/pause"                 2 days ago       Up 2 days                 k8s_POD_kubernetes-dashboard-67484c44f6-brz2z_kubernetes-dashboard_bb016e8e-a4b1-48e6-912c-022addfb72bf_0
dbec965d88da   registry.cn-beijing.aliyuncs.com/dotbalo/node                         "start_runit"            3 days ago       Up 3 days                 k8s_calico-node_calico-node-gn8ws_kube-system_16eeb29c-3383-4e62-b84c-40bf3dae7d07_0
610909969be1   registry.cn-hangzhou.aliyuncs.com/google_containers/pause-amd64:3.2   "/pause"                 3 days ago       Up 3 days                 k8s_POD_calico-node-gn8ws_kube-system_16eeb29c-3383-4e62-b84c-40bf3dae7d07_0

进入容器

[root@k8s-master01 ~]# docker exec -ti 2ef850f11136 sh
# ls
bin  boot  dev	etc  home  lib	lib64  media  mnt  opt	proc  root  run  sbin  srv  sys  tmp  usr  var
# exit
[root@k8s-master01 ~]# 

复制文件

后台启动nginx

[root@k8s-master01 ~]# docker run -tid -p 12345:80 nginx:latest
b75ad319e61326e05905d41d67616112be51af4d1234f51bef5d21807e9bc42d
[root@k8s-master01 ~]# docker ps
CONTAINER ID   IMAGE                                                                 COMMAND                  CREATED         STATUS         PORTS                   NAMES
b75ad319e613   nginx:latest                                                          "/docker-entrypoint.…"   8 seconds ago   Up 6 seconds   0.0.0.0:12345->80/tcp   upbeat_brahmagupta

访问地址:http://192.168.232.128:12345/

进入容器

[root@k8s-master01 ~]# docker exec -ti b75ad319e613 bash
root@b75ad319e613:/# cd /usr/share/nginx/html/
root@b75ad319e613:/usr/share/nginx/html# ls
50x.html  index.html
root@b75ad319e613:/usr/share/nginx/html# exit
exit

复制文件到容器中

[root@k8s-master01 ~]# echo "test cp" > index.html
[root@k8s-master01 ~]# docker cp index.html b75ad319e613:/usr/share/nginx/html/

访问地址:http://192.168.232.128:12345/

复制容器中的文件到本地

[root@k8s-master01 ~]# docker cp b75ad319e613:/usr/share/nginx/html/index.html .

删除镜像

[root@k8s-master01 ~]# docker images
REPOSITORY                                                        TAG       IMAGE ID       CREATED         SIZE
nginx                                                             latest    4cdc5dd7eaad   8 days ago      133MB

[root@k8s-master01 ~]# docker rmi 4cdc5dd7eaad
Error response from daemon: conflict: unable to delete 4cdc5dd7eaad (cannot be forced) - image is being used by running container b75ad319e613

# 删除容器
[root@k8s-master01 ~]# docker rm b75ad319e613
Error response from daemon: You cannot remove a running container b75ad319e61326e05905d41d67616112be51af4d1234f51bef5d21807e9bc42d. Stop the container before attempting removal or force remove

# 停止容器运行
[root@k8s-master01 ~]# docker stop b75ad319e613
b75ad319e613

[root@k8s-master01 ~]# docker rm b75ad319e613
b75ad319e613

[root@k8s-master01 ~]# docker rmi 4cdc5dd7eaad
Error response from daemon: conflict: unable to delete 4cdc5dd7eaad (must be forced) - image is being used by stopped container cd2a20f47459

[root@k8s-master01 ~]# docker rm cd2a20f47459
cd2a20f47459

[root@k8s-master01 ~]# docker rmi 4cdc5dd7eaad
Untagged: nginx:latest
Untagged: nginx@sha256:353c20f74d9b6aee359f30e8e4f69c3d7eaea2f610681c4a95849a2fd7c497f9
Deleted: sha256:4cdc5dd7eaadff5080649e8d0014f2f8d36d4ddf2eff2fdf577dd13da85c5d2f
Deleted: sha256:63d268dd303e176ba45c810247966ff8d1cb9a5bce4a404584087ec01c63de15
Deleted: sha256:b27eb5bbca70862681631b492735bac31d3c1c558c774aca9c0e36f1b50ba915
Deleted: sha256:435c6dad68b58885ad437e5f35f53e071213134eb9e4932b445eac7b39170700
Deleted: sha256:bdf28aff423adfe7c6cb938eced2f19a32efa9fa3922a3c5ddce584b139dc864
Deleted: sha256:2c78bcd3187437a7a5d9d8dbf555b3574ba7d143c1852860f9df0a46d5df056a
Deleted: sha256:764055ebc9a7a290b64d17cf9ea550f1099c202d83795aa967428ebdf335c9f7

修改记录

[root@k8s-master01 ~]# docker images
registry.cn-hangzhou.aliyuncs.com/google_containers/pause-amd64   3.2       80d28bedfe5d   17 months ago   683kB

[root@k8s-master01 ~]# docker history registry.cn-hangzhou.aliyuncs.com/google_containers/pause-amd64:3.2
IMAGE          CREATED         CREATED BY                              SIZE      COMMENT
80d28bedfe5d   17 months ago   ENTRYPOINT ["/pause"]                   0B        buildkit.dockerfile.v0
<missing>      17 months ago   ADD bin/pause-amd64 /pause # buildkit   683kB     buildkit.dockerfile.v0
<missing>      17 months ago   ARG ARCH                                0B        buildkit.dockerfile.v0

保存状态

假设我们复制了文件到容器中,想要保存容器状态需要使用 docker commit

# 拉取镜像
[root@k8s-master01 ~]# docker pull nginx:latest
latest: Pulling from library/nginx
b4d181a07f80: Pull complete 
66b1c490df3f: Pull complete 
d0f91ae9b44c: Pull complete 
baf987068537: Pull complete 
6bbc76cbebeb: Pull complete 
32b766478bc2: Pull complete 
Digest: sha256:353c20f74d9b6aee359f30e8e4f69c3d7eaea2f610681c4a95849a2fd7c497f9
Status: Downloaded newer image for nginx:latest
docker.io/library/nginx:latest

# 后台启动容器
[root@k8s-master01 ~]# docker run -tid -p 12345:80 nginx:latest
8ddcc9d728450c9398579155e793aca873713632d72a8402e5684ebb6f613437

# 获取容器ID
[root@k8s-master01 ~]# docker ps
CONTAINER ID   IMAGE                                                                 COMMAND                  CREATED          STATUS          PORTS                   NAMES
8ddcc9d72845   nginx:latest                                                          "/docker-entrypoint.…"   28 seconds ago   Up 27 seconds   0.0.0.0:12345->80/tcp   confident_leavitt

# 复制文件到容器中
[root@k8s-master01 ~]# docker cp index.html 8ddcc9d72845:/usr/share/nginx/html/

# 提交修改记录
[root@k8s-master01 ~]# docker commit -a "mingsonzheng" -m  "update index.html" 8ddcc9d72845 nginx:commit
sha256:f62c69e4853e45951b1b83eec2432e48e436d65a14a62b087e5fe6c7c9398771

# 查看镜像
[root@k8s-master01 ~]# docker images
REPOSITORY                                                        TAG       IMAGE ID       CREATED          SIZE
nginx                                                             commit    f62c69e4853e   40 seconds ago   133MB

# 启动容器,加上--rm,则关闭之后会删除,不会产生大量状态为Exited的容器
[root@k8s-master01 ~]# docker run -ti --rm nginx:commit bash
root@c657e57078c1:/# cd /usr/share/nginx/html/
root@c657e57078c1:/usr/share/nginx/html# ls
50x.html  index.html
root@c657e57078c1:/usr/share/nginx/html# exit
exit

# 查看容器,该容器不会出现在列表中
[root@k8s-master01 ~]# docker ps

Dockerfile用法

  • Dockerfile指令
  • Dockerfile用法

Dockerfile指令

  • FROM:继承基础镜像
  • MAINTAINER:镜像制作作者信息
  • RUN:用来执行shell命令
  • EXPOSE:暴露端口号
  • CMD:启动容器默认执行的命令
  • ENTRYPOINT:启动容器真正执行的命令
  • VOLUME:创建挂载点
  • ENV:配置环境变量
  • ADD:添加文件到容器
  • COPY:复制文件到容器
  • WORKDIR:设置容器的工作目录
  • USER:容器使用的用户

nginx官方Dockerfile:https://github.com/nginxinc/docker-nginx/blob/master/Dockerfile-alpine.template

继承alpine基础镜像

FROM alpine:%%ALPINE_VERSION%%

MAINTAINER:镜像制作作者信息,新版本推荐使用LABEL

LABEL maintainer="NGINX Docker Maintainers <docker-maint@nginx.com>"

执行shell命令

RUN set -x

apk是alpine安装包的工具

apk add --no-cache --virtual .cert-deps

暴露端口号

EXPOSE 80

启动容器默认执行的命令

CMD ["nginx", "-g", "daemon off;"]

CMD命令可以被覆盖,比如bash

[root@k8s-master01 ~]# docker run -ti --rm nginx:commit bash

CMD 和 ENTRYPOINT 必须有一个,如果两者都有的话,ENTRYPOINT 就是启动命令,而 CMD 就是它的参数

ENTRYPOINT 对应 k8s 的 COMMAND

CMD 对应 k8s 的 arg

VOLUME 是一个匿名的挂载点,Docker 不建议保留容器产生的文件,但是有一些文件是必须保留的,比如数据库,我们可以为其创建一个挂载点,将宿主机的目录挂载到容器里面,这样就可以保留它的数据

配置环境变量

ENV NGINX_VERSION %%NGINX_VERSION%%
ENV NJS_VERSION   %%NJS_VERSION%%
ENV PKG_RELEASE   %%PKG_RELEASE%%

但是不建议写在 Dockerfile 中,建议通过命令行 -e 传入参数,独立到镜像之外,可以动态修改

[root@k8s-master01 ~]# docker run -ti -e a=b -e c=d

ADD:复制文件到容器,如果复制压缩文件会自动解压

COPY:复制文件到容器,不会解压,直接复制

WORKDIR:设置容器的工作目录,如果有设置则进入容器时会进入到该目录下

USER:容器使用的用户,系统默认用户是root,但是在业务容器容器化的时候不建议使用root,因为不安全,可能会造成对宿主机有危险的操作

[root@k8s-master01 ~]# whoami
root

Dockerfile用法

新增Dockerfile

[root@k8s-master01 ~]# mkdir dockerfiles
[root@k8s-master01 ~]# cd dockerfiles/
[root@k8s-master01 dockerfiles]# vim Dockerfile
# 添加以下内容
FROM centos:8

LABEL maintainer="test dockerfile"
LABEL test=dockerfile

RUN useradd mingsonzheng
RUN mkdir /opt/mingsonzheng

在当前目录下构建镜像

[root@k8s-master01 dockerfiles]# docker build -t centos:user .
Sending build context to Docker daemon  2.048kB
Step 1/5 : FROM centos:8
 ---> 300e315adb2f
Step 2/5 : LABEL maintainer="test dockerfile"
 ---> Running in cccd20f9b0f5
Removing intermediate container cccd20f9b0f5
 ---> f6dc016add09
Step 3/5 : LABEL test=dockerfile
 ---> Running in e4d1962c630b
Removing intermediate container e4d1962c630b
 ---> 3977dc88a2f2
Step 4/5 : RUN useradd mingsonzheng
 ---> Running in d3905f2c7dc4
Removing intermediate container d3905f2c7dc4
 ---> 30968f5c2285
Step 5/5 : RUN mkdir /opt/mingsonzheng
 ---> Running in 811c4ceb3e70
Removing intermediate container 811c4ceb3e70
 ---> 0cd811c2fadf
Successfully built 0cd811c2fadf
Successfully tagged centos:user

启动镜像

[root@k8s-master01 dockerfiles]# docker run -ti --rm centos:user bash
[root@828f29ae30bf /]# 

调试的时候一定要加上 –rm,不然会有很多Exited记录

查看用户

[root@828f29ae30bf /]# cat /etc/passwd
mingsonzheng:x:1000:1000::/home/mingsonzheng:/bin/bash

制作完镜像之后,如果调试没有问题,记得推送到镜像仓库

如果测试通过之后,需要优化一下RUN语句,没有必要分开写,因为docker有缓存机制,假设有20个RUN语句,执行第18个的时候失败了,前面17个执行成功的没有必要再执行一次,修改之后直接从第18个RUN语句继续执行

[root@k8s-master01 dockerfiles]# vim Dockerfile 
# 修改为以下内容
FROM centos:8

LABEL maintainer="test dockerfile"
LABEL test=dockerfile

#RUN useradd mingsonzheng
#RUN mkdir /opt/mingsonzheng
RUN useradd mingsonzheng && /opt/mingsonzheng

这样docker的层级会少一层,存储大小会小一点

CMD:启动容器默认执行的命令

[root@k8s-master01 dockerfiles]# vim Dockerfile 
# 修改为以下内容
FROM centos:8

LABEL maintainer="test dockerfile"
LABEL test=dockerfile

RUN useradd mingsonzheng
RUN mkdir /opt/mingsonzheng

CMD [ "sh", "-c", "echo 1"]

#RUN useradd mingsonzheng && /opt/mingsonzheng

构建镜像

[root@k8s-master01 dockerfiles]# docker build -t centos:cmd .

如果文件不在当前目录,可以使用-f

[root@k8s-master01 dockerfiles]# mkdir t
[root@k8s-master01 dockerfiles]# cp Dockerfile t
[root@k8s-master01 dockerfiles]# docker build -t centos:cmd -f t/Dockerfile

查看镜像

[root@k8s-master01 dockerfiles]# docker images
REPOSITORY                                                        TAG       IMAGE ID       CREATED         SIZE
centos                                                            cmd       a008df4670f8   2 minutes ago   210MB

启动容器

[root@k8s-master01 dockerfiles]# docker run -ti --rm centos:cmd
1

可以看到打印了一个1就退出了

使用bash覆盖CMD命令

[root@k8s-master01 dockerfiles]# docker run -ti --rm centos:cmd bash
[root@924006c7dc0e /]# exit
exit

可以看到它就不打印了,覆盖了CMD命令

在k8s中不建议将CMD命令打到镜像中,因为我们遵循的构建策略是一次构建到处运行,启动的命令可能不是统一的,可以指定配置文件让启动命令根据配置文件变成不同环境的命令,这样可以使用k8s的arg或者cmd去覆盖掉它的启动参数,所以CMD可以不打到镜像中,当然也可以使用变量的注入方式

使用ENTRYPIOINT,CMD可以被覆盖,如果有ENTRYPIOINT的话,CMD就是ENTRYPIOINT的参数

[root@k8s-master01 dockerfiles]# vim Dockerfile 
# 修改为以下内容
FROM centos:8

LABEL maintainer="test dockerfile"
LABEL test=dockerfile

RUN useradd mingsonzheng
RUN mkdir /opt/mingsonzheng

ENTRYPOINT ["echo"]

CMD [ "3"]

#RUN useradd mingsonzheng && /opt/mingsonzheng

打包镜像

[root@k8s-master01 dockerfiles]# docker build -t centos:ep .

运行容器

[root@k8s-master01 dockerfiles]# docker run -ti --rm centos:ep 10
10
[root@k8s-master01 dockerfiles]# docker run -ti --rm centos:ep mingsonzheng
mingsonzheng

可以看到CMD就是ENTRYPIOINT的参数,CMD可以被覆盖,我们可以把命令相同的部分打入到ENTRYPIOINT,不同的部分通过CMD覆盖

ENV:配置环境变量

[root@k8s-master01 dockerfiles]# vim Dockerfile 
# 修改为以下内容
FROM centos:8

LABEL maintainer="test dockerfile"
LABEL test=dockerfile

ENV test_env1 env1
ENV test_env2 env2

RUN useradd mingsonzheng
RUN mkdir /opt/mingsonzheng

#ENTRYPOINT ["echo"]

CMD echo "test_env1 test_env2"

#RUN useradd mingsonzheng && /opt/mingsonzheng

构建镜像

[root@k8s-master01 dockerfiles]# docker build -t centos:env .

启动容器

[root@k8s-master01 dockerfiles]# docker run -ti --rm centos:env
test_env1 test_env2

环境变量也可以这么写

ENV env1=test1 env2=test2

正式应用的ENV变量不要写在Dockerfile里面,应该使用k8s资源文件,或者docker的-e参数注入进去,这样也能减少构建镜像的层数

ADD:添加文件到容器

# 新增文件
[root@k8s-master01 dockerfiles]# echo 123 > index.html

# 压缩文件
[root@k8s-master01 dockerfiles]# tar zcf index.tar.gz index.html t/

# 编辑Dockerfile
[root@k8s-master01 dockerfiles]# vim Dockerfile 
# 修改为以下内容
FROM centos:8

LABEL maintainer="test dockerfile"
LABEL test=dockerfile

ENV test_env1 env1
ENV test_env2 env2

RUN useradd mingsonzheng
RUN mkdir /opt/mingsonzheng

#ENTRYPOINT ["echo"]
ENV env1=test1 env2=test2

ADD ./index.tar.gz /opt/

CMD echo "test_env1 test_env2"

#RUN useradd mingsonzheng && /opt/mingsonzheng

构建镜像

[root@k8s-master01 dockerfiles]# docker build -t centos:add .

启动容器

[root@k8s-master01 dockerfiles]# docker run -ti --rm centos:add bash
[root@b2dacca0f34f /]# cd /opt/
[root@b2dacca0f34f opt]# ls
index.html  mingsonzheng  t

可以看到文件被复制到容器的指定目录下,并且自动解压了

COPY:复制文件到容器

[root@k8s-master01 dockerfiles]# vim Dockerfile 
# 修改为以下内容
FROM centos:8

LABEL maintainer="test dockerfile"
LABEL test=dockerfile

ENV test_env1 env1
ENV test_env2 env2

RUN useradd mingsonzheng
RUN mkdir /opt/mingsonzheng

#ENTRYPOINT ["echo"]
ENV env1=test1 env2=test2

ADD ./index.tar.gz /opt/
COPY ./t /opt/mingsonzheng/
CMD echo "test_env1 test_env2"

#RUN useradd mingsonzheng && /opt/mingsonzheng

构建镜像

[root@k8s-master01 dockerfiles]# docker build -t centos:add .

启动容器

[root@k8s-master01 dockerfiles]# docker run -ti --rm centos:add bash
[root@3ca8cddbf8b3 /]# cd /opt/mingsonzheng/
[root@3ca8cddbf8b3 mingsonzheng]# ls
Dockerfile

可以看到docker把t目录下的文件复制进来了,并不会复制目录,如果想要复制目录的话,只能多加一层目录

COPY复制压缩文件的话不会解压

docker build的时候会把当前目录下所有东西发送到内存中,所以文件必须要放在执行docker build命令的文件目录下

WORKDIR:设置容器的工作目录

[root@k8s-master01 dockerfiles]# vim Dockerfile 
# 修改为以下内容
FROM centos:8

LABEL maintainer="test dockerfile"
LABEL test=dockerfile

ENV test_env1 env1
ENV test_env2 env2

RUN useradd mingsonzheng
RUN mkdir /opt/mingsonzheng

#ENTRYPOINT ["echo"]
ENV env1=test1 env2=test2

ADD ./index.tar.gz /opt/
COPY ./t /opt/mingsonzheng/
CMD echo "test_env1 test_env2"
WORKDIR /opt/mingsonzheng
CMD pwd ; ls
#RUN useradd mingsonzheng && /opt/mingsonzheng

构建镜像

[root@k8s-master01 dockerfiles]# docker build -t centos:workdir .

启动容器

[root@k8s-master01 dockerfiles]# docker run -ti --rm centos:workdir
/opt/mingsonzheng
Dockerfile

USER:容器使用的用户

# 启动容器
[root@k8s-master01 dockerfiles]# docker run -ti --rm centos:workdir bash

# 查看当前用户
[root@87983e2581da mingsonzheng]# whoami
root

# 查看系统其他用户
[root@87983e2581da mingsonzheng]# cat /etc/passwd
mingsonzheng:x:1000:1000::/home/mingsonzheng:/bin/bash

切换用户

[root@k8s-master01 dockerfiles]# vim Dockerfile 
# 修改为以下内容
FROM centos:8

LABEL maintainer="test dockerfile"
LABEL test=dockerfile

ENV test_env1 env1
ENV test_env2 env2

RUN useradd mingsonzheng
RUN mkdir /opt/mingsonzheng

#ENTRYPOINT ["echo"]
ENV env1=test1 env2=test2

ADD ./index.tar.gz /opt/
COPY ./t /opt/mingsonzheng/
CMD echo "test_env1 test_env2"
WORKDIR /opt/mingsonzheng
USER 1000
CMD pwd ; ls
#RUN useradd mingsonzheng && /opt/mingsonzheng

构建镜像

[root@k8s-master01 dockerfiles]# docker build -t centos:workdir .

启动容器

[root@k8s-master01 dockerfiles]# docker run -ti --rm centos:workdir bash
[mingsonzheng@f6110f7e8e3a mingsonzheng]$ whoami
mingsonzheng

使用镜像仓库地址(xxx.com)构建镜像

[root@k8s-master01 dockerfiles]# docker build -t xxx.com/centos:workdir .

查看镜像

[root@k8s-master01 dockerfiles]# docker images
REPOSITORY                                                        TAG       IMAGE ID       CREATED          SIZE
xxx.com/centos                                                    workdir   cf9572a3833e   3 minutes ago    210MB

VOLUME:创建挂载点

[root@k8s-master01 dockerfiles]# vim Dockerfile 
# 修改为以下内容
FROM centos:8

LABEL maintainer="test dockerfile"
LABEL test=dockerfile

ENV test_env1 env1
ENV test_env2 env2

RUN useradd mingsonzheng
RUN mkdir /opt/mingsonzheng

#ENTRYPOINT ["echo"]
ENV env1=test1 env2=test2

ADD ./index.tar.gz /opt/
COPY ./t /opt/mingsonzheng/
CMD echo "test_env1 test_env2"
WORKDIR /opt/mingsonzheng
#USER 1000
VOLUME /data
CMD pwd ; ls
#RUN useradd mingsonzheng && /opt/mingsonzheng

构建镜像

[root@k8s-master01 dockerfiles]# docker build -t centos:workdir .

启动容器

[root@k8s-master01 dockerfiles]# docker run -ti --rm centos:workdir bash
[root@6aecced2b780 mingsonzheng]# cd /    
[root@6aecced2b780 /]# ls
bin  data  dev	etc  home  lib	lib64  lost+found  media  mnt  opt  proc  root	run  sbin  srv	sys  tmp  usr  var

可以看到data目录,它会与本地 /var/lib/docker/volumes/ 的目录下生成一个volume的目录,然后挂载到容器中的data下,退出容器则会清除本地目录下的data

通过-v将mysql_data目录挂载到容器中,使用-v则系统不会自动创建挂载目录

[root@k8s-master01 ~]# mkdir mysql_data
[root@k8s-master01 ~]# docker run -ti -v /root/mysql_data/:/data xxx.com/centos:workdir bash

制作小镜像

一定不要使用centos基础镜像,可以使用alpine,busybox,scratch,debian

修改基础镜像

[root@k8s-master01 dockerfiles]# vim Dockerfile 
# 修改为以下内容
#FROM centos:8
FROM alpine:3.8

LABEL maintainer="test dockerfile"
LABEL test=dockerfile

ENV test_env1 env1
ENV test_env2 env2

RUN adduser -D mingsonzheng
RUN mkdir -p /opt/mingsonzheng

#ENTRYPOINT ["echo"]
ENV env1=test1 env2=test2

ADD ./index.tar.gz /opt/
COPY ./t /opt/mingsonzheng/
WORKDIR /opt/mingsonzheng
#USER 1000
VOLUME /data
CMD pwd ; ls
#RUN useradd mingsonzheng && /opt/mingsonzheng

构建镜像

[root@k8s-master01 dockerfiles]# docker build -t centos:workdir .

查看镜像

[root@k8s-master01 dockerfiles]# docker images
REPOSITORY                                                        TAG       IMAGE ID       CREATED             SIZE
alpine                                                            workdir   7fc05207414a   22 seconds ago      4.42MB
centos                                                            workdir   b165153a0132   36 minutes ago      210MB

alpine与centos相比,SIZE非常小,适合做为基础镜像,基础镜像可以在官方仓库查找,不需要自己制作

如果需要用到glibc,可以使用node:slim,python:slim,net作为基础镜像

多阶段制作小镜像

分开两个步骤:编译操作和生成最终镜像的操作

新建一个go文件

[root@k8s-master01 dockerfiles]# vim main.go
# 修改为以下内容
package main

import "fmt"

func main() {  
    fmt.Println("Hello World")
}

新建一个Dockerfile文件

[root@k8s-master01 dockerfiles]# mv Dockerfile t/123
[root@k8s-master01 dockerfiles]# vim Dockerfile
# 修改为以下内容
FROM golang:1.14.4-alpine

WORKDIR /opt

COPY main.go /opt

RUN go build /opt/main.go

CMD "./main"

构建镜像

[root@k8s-master01 dockerfiles]# docker build -t hello:single_build .

启动容器

[root@k8s-master01 dockerfiles]# docker run -ti --rm hello:single_build
Hello World

查看镜像

[root@k8s-master01 dockerfiles]# docker images
REPOSITORY                                                        TAG             IMAGE ID       CREATED             SIZE
hello                                                             single_build    ca11178a0c13   44 seconds ago      372MB

查看包大小

[root@k8s-master01 dockerfiles]# docker run -ti --rm hello:single_build sh
/opt # ls -lh
total 2M     
-rwxr-xr-x    1 root     root        2.0M Jul 16 08:30 main
-rw-r--r--    1 root     root          77 Jul 16 08:24 main.go
/opt # 

2M的包生成的镜像有372M,我们应该使用分阶段构建

[root@k8s-master01 dockerfiles]# vim Dockerfile
# 修改为以下内容
# build step
FROM golang:1.14.4-alpine

WORKDIR /opt

COPY main.go /opt

RUN go build /opt/main.go

CMD "./main"

# create real app image

FROM alpine:3.8

COPY --from=0 /opt/main /

CMD "./opt/main"

–from=0就是第一步的操作(# create real app image上面的操作)

构建镜像

[root@k8s-master01 dockerfiles]# docker build -t hello:alpine .

启动容器

[root@k8s-master01 dockerfiles]# docker run -ti --rm hello:alpine sh
/ # ls
bin    dev    etc    home   lib    main   media  mnt    proc   root   run    sbin   srv    sys    tmp    usr    var
/ # ./main
Hello World

查看镜像

[root@k8s-master01 dockerfiles]# docker images
REPOSITORY                                                        TAG             IMAGE ID       CREATED              SIZE
hello                                                             alpine          66fa14e35f3c   About a minute ago   6.48MB
hello                                                             single_build    ca11178a0c13   11 minutes ago       372MB

可以看到单阶段和多阶段镜像大小的区别,所以一定要进行分阶段构建

使用builder命令复制包到根目录

[root@k8s-master01 dockerfiles]# vim Dockerfile
# 修改为以下内容
# build step
FROM golang:1.14.4-alpine as builder

WORKDIR /opt

COPY main.go /opt

RUN go build /opt/main.go

CMD "./main"

# create real app image

FROM alpine:3.8

COPY --from=builder /opt/main /

CMD "./opt/main"

构建镜像

[root@k8s-master01 dockerfiles]# docker build -t hello:alpine .

查看镜像

[root@k8s-master01 dockerfiles]# docker images
REPOSITORY                                                        TAG             IMAGE ID       CREATED             SIZE
hello                                                             alpine          66fa14e35f3c   9 minutes ago       6.48MB

镜像大小和前面的差别不大,我们只是将第一个步骤打包成镜像,然后把它里面的文件复制到现在的镜像里面

php Dockerfile

[root@k8s-master01 dockerfiles]# mv Dockerfile goDockerfile
[root@k8s-master01 dockerfiles]# vim Dockerfile
# 修改为以下内容
FROM php:7.1.22-fpm-alpine

RUN apk add --no-cache binutils freetype libpng libjpeg-turbo freetype-dev libpng-dev libjpeg-turbo-dev libc6-compat libxml2 libxml2-dev libmcrypt libmcrypt-dev     libc-dev   icu-dev gettext-dev  openssl-dev bzip2-dev

RUN docker-php-ext-install pdo pdo_mysql mcrypt zip gd pcntl opcache bcmath
#RUN docker-php-ext-install gettext
RUN docker-php-ext-install mysqli
#RUN apk add --no-cache php7-sysvsem php7-pdo_dblib  php7-sockets php-soap php7-xmlrpc
##RUN apk add --no-cache php7-sysvsem php7-pdo_dblib  php7-sockets php-soap php7-xmlrpc
##RUN apk add --no-cache freetds-dev
##RUN docker-php-ext-install pdo_dblib
#RUN docker-php-ext-install soap
#RUN docker-php-ext-install sockets
#RUN docker-php-ext-install sysvsem
#RUN docker-php-ext-install xmlrpc
#RUN apk add --no-cache freetds-dev
#RUN docker-php-ext-install pdo_dblib
#RUN docker-php-ext-configure gd --with-freetype-dir=/usr/include/ --with-jpeg-dir=/usr/include/
#RUN docker-php-ext-install -j$(nproc) gd
#FROM php:7.1.22-fpm-alpine

#COPY --from=0 /usr/local/lib/php/extensions/no-debug-non-zts-20160303 /usr/local/lib/php/extensions/no-debug-non-zts-20160303

#RUN apk add --no-cache freetds-dev php7-sysvsem php7-pdo_dblib  php7-sockets php-soap php7-xmlrpc binutils freetype libpng libjpeg-turbo freetype-dev libpng-dev libjpeg-turbo-dev libc6-compat libxml2 libxml2-dev libmcrypt libmcrypt-dev     libc-dev   icu-dev gettext-dev  openssl-dev bzip2-dev && cd /usr/local/lib/php/extensions/no-debug-non-zts-20160303 && docker-php-ext-enable *.so  && rm -rf /var/cache/apk/*
  • 第一步是选择基础镜像php:7.1.22-fpm-alpine
  • 第二步是根据基础镜像安装依赖环境,php的一堆扩展包

多阶段的就是编译在一个镜像里面完成,第二个镜像使用第一个镜像编译的产物,省去了编译产生的缓存

Scratch空镜像

Scratch空镜像不可拉取,但是可以直接使用

使用scratch

[root@k8s-master01 dockerfiles]# cp Dockerfile t/phpDockerfile

[root@k8s-master01 dockerfiles]# cp goDockerfile Dockerfile
cp: overwrite ‘Dockerfile’? y

[root@k8s-master01 dockerfiles]# vim Dockerfile 
# 修改为以下内容
# build step
FROM golang:1.14.4-alpine as builder

WORKDIR /opt

COPY main.go /opt

RUN go build /opt/main.go

CMD "./main"

# create real app image

FROM scratch

COPY --from=builder /opt/main /

CMD "./main"

构建镜像

[root@k8s-master01 dockerfiles]# docker build -t hello:scratch .

查看镜像

[root@k8s-master01 dockerfiles]# docker images
REPOSITORY   TAG             IMAGE ID       CREATED              SIZE
hello        scratch         4d747be3b21b   About a minute ago   2.07MB

启动容器

[root@k8s-master01 dockerfiles]# docker run -ti --rm hello:scratch /main
Hello World

基于最基础的镜像,制作依赖环境的镜像可以使用,但是建议使用官方制作好的镜像

如果Dockerfile中引用的镜像发生了更新,需要使用pull参数