docker常用命令及镜像的制作与上传

1. 安装及使用docker

1.1 dockers安装

[root@vm1 ~]# yum -y install yum-utils
[root@vm1 ~]# yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
[root@vm1 ~]# yum clean all
[root@vm1 ~]# yum makecache fast
[root@vm1 ~]# yum -y install docker-ce docker-ce-cli containerd.io
[root@vm1 ~]# systemctl enable --now docker
[root@vm1 ~]# systemctl status docker
● docker.service - Docker Application Container Engine
   Loaded: loaded (/usr/lib/systemd/system/docker.service; enabled; vendor preset: disabled)
   Active: active (running) since Thu 2020-08-27 21:32:17 EDT; 25s ago
     Docs: https://docs.docker.com
 Main PID: 12387 (dockerd)
    Tasks: 8
   Memory: 41.8M
   CGroup: /system.slice/docker.service
           └─12387 /usr/bin/dockerd -H fd:// --containerd=/run/containe...

Aug 27 21:32:16 vm1 dockerd[12387]: time="2020-08-27T21:32:16.60153352...c
Aug 27 21:32:16 vm1 dockerd[12387]: time="2020-08-27T21:32:16.60160606...c
Aug 27 21:32:16 vm1 dockerd[12387]: time="2020-08-27T21:32:16.60161997...c
Aug 27 21:32:16 vm1 dockerd[12387]: time="2020-08-27T21:32:16.62342627..."
Aug 27 21:32:16 vm1 dockerd[12387]: time="2020-08-27T21:32:16.91929153..."
Aug 27 21:32:17 vm1 dockerd[12387]: time="2020-08-27T21:32:17.18048845..."
Aug 27 21:32:17 vm1 dockerd[12387]: time="2020-08-27T21:32:17.20097042...2
Aug 27 21:32:17 vm1 dockerd[12387]: time="2020-08-27T21:32:17.20115804..."
Aug 27 21:32:17 vm1 dockerd[12387]: time="2020-08-27T21:32:17.25775916..."
Aug 27 21:32:17 vm1 systemd[1]: Started Docker Application Container ...e.
Hint: Some lines were ellipsized, use -l to show in full.

1.2 docker加速

docker-ce的配置文是/etc/docker/daemon.json,此文件默认不存在,需要我们手动创建并进行配置,而docker的加速就是通过配置此文件来实现的。

docker的加速有多种方式:

  • 网易:https://hub-mirror.c.163.com/
  • 阿里云:https://<你的ID>.mirror.aliyuncs.com(需要阿里云账号)
  • 中科大:https://docker.mirrors.ustc.edu.cn
[root@vm1 ~]# cat /etc/docker/daemon.json
{
  "registry-mirrors": ["https://pee6w651.mirror.aliyuncs.com/"]
}

[root@vm1 ~]# systemctl daemon-reload 
[root@vm1 ~]#  systemctl restart docker
[root@vm1 ~]# docker info
[root@localhost ~]# docker info
Client:
 Debug Mode: false

Server:
 Containers: 0
  Running: 0
  Paused: 0
  Stopped: 0
 Images: 0
 Server Version: 19.03.12
 Storage Driver: overlay2
  Backing Filesystem: xfs
  Supports d_type: true
  Native Overlay Diff: true
 Logging Driver: json-file
 Cgroup Driver: cgroupfs
 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: runc
 Default Runtime: runc
 Init Binary: docker-init
 containerd version: 7ad184331fa3e55e52b890ea95e65ba581ae3429
 runc version: dc9208a3303feef5b3839f4323d9beb36df0a9dd
 init version: fec3683
 Security Options:
  seccomp
   Profile: default
 Kernel Version: 3.10.0-862.el7.x86_64
 Operating System: CentOS Linux 7 (Core)
 OSType: linux
 Architecture: x86_64
 CPUs: 1
 Total Memory: 1.779GiB
 Name: localhost.localdomain
 ID: 45E5:67QK:VTXS:SFXB:XIDF:HOEN:RK6C:UTYW:JFUP:Q7BS:SGXO:CG73
 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
 Registry Mirrors:
  https://pee6w651.mirror.aliyuncs.com/
 Live Restore Enabled: false    

1.3 docker常用操作

可参考菜鸟教程

命令功能
docker searchSearch the Docker Hub for images
docker pullPull an image or a repository from a registry
docker imagesList images
docker createCreate a new conntainer
docker startStart one or more stopped containers
docker runRun a command in a new container
docker attachAttach to a runninng container
docker psList containers
docker logsFetch the logs of a container
docker restartRestart a container
docker stopStop one or more running containers
docker killKill one or more running containers
docker rmRemove onne or more containers
docker execRun a command in a running container
docker infoDisplay system-wide information
docker inspectReturn low-level information on Docker objects
  1. docker search //查找镜像
[root@vm1 ~]# docker search nginx
NAME                               DESCRIPTION                                     STARS               OFFICIAL            AUTOMATED
nginx                              Official build of Nginx.                        13662               [OK]                
jwilder/nginx-proxy                Automated Nginx reverse proxy for docker con…   1866                                    [OK]
richarvey/nginx-php-fpm            Container running Nginx + PHP-FPM capable of…   782                                     [OK]
linuxserver/nginx                  An Nginx container, brought to you by LinuxS…   127                                     
bitnami/nginx                      Bitnami nginx Docker Image                      89                                      [OK]          

  1. docker pull // 从镜像仓库中拉取镜像
[root@vm1 ~]# docker pull nginx
Using default tag: latest
latest: Pulling from library/nginx
bf5952930446: Pull complete 
cb9a6de05e5a: Pull complete 
9513ea0afb93: Pull complete 
b49ea07d2e93: Pull complete 
a5e4a503d449: Pull complete 
Digest: sha256:b0ad43f7ee5edbc0effbc14645ae7055e21bc1973aee5150745632a24a752661
Status: Downloaded newer image for nginx:latest
docker.io/library/nginx:latest
  1. docker images // 列出本地镜像
[root@vm1 ~]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
nginx               latest              4bb46517cac3        12 days ago         133MB
  1. docker create //创建一个新的容器但不启动
[root@vm1 ~]# docker create  --name y1  nginx:latest
e2caa3f5f3382fc3bb0dbf67fc2556d74a8fe9cb498c6e2d104b7c2fd87dca41
  1. docker start //启动容器
[root@vm1 ~]# docker start y1
y1
[root@localhost ~]# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED              STATUS              PORTS               NAMES
e2caa3f5f338        nginx:latest        "/docker-entrypoint.…"   About a minute ago   Up 2 seconds        80/tcp              y1
  1. docker run -it //创建一个新的容器并运行一个命令
[root@vm1 ~]# docker run -it nginx:latest /bin/bash
root@e7ae58242760:/# ls
bin   docker-entrypoint.d   home   media  proc	sbin  tmp
boot  docker-entrypoint.sh  lib    mnt	  root	srv   usr
dev   etc		    lib64  opt	  run	sys   var

7.docker attach //连接到正在运行中的容器

[root@vm1 ~]# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS               NAMES
e7ae58242760        nginx:latest        "/docker-entrypoint.…"   6 minutes ago       Up 6 minutes        80/tcp              musing_saha
[root@localhost ~]# docker attach e7ae58242760
root@e7ae58242760:/# ls
bin   docker-entrypoint.d   home   media  proc	sbin  tmp
boot  docker-entrypoint.sh  lib    mnt	  root	srv   usr

8 .docker ps //列出容器

[root@vm1 ~]# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS               NAMES
25622c5bff24        nginx:latest        "/docker-entrypoint.…"   6 seconds ago       Up 5 seconds        80/tcp              infallible_thompson

9.docker logs //获取容器的日志

[root@vm1 ~]# docker logs y1
/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: Getting the checksum of /etc/nginx/conf.d/default.conf
10-listen-on-ipv6-by-default.sh: 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: Configuration complete; ready for start up
  1. docker kill //杀掉一个运行中的容器
[root@vm1 ~]# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS               NAMES
25622c5bff24        nginx:latest        "/docker-entrypoint.…"   4 minutes ago       Up 4 minutes        80/tcp              infallible_thompson
[root@vm1 ~]# docker kill 25622c5bff24
25622c5bff24
[root@localhost ~]# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
  1. docker rm //删除一个或多个容器
[root@vm1 ~]# docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                            PORTS               NAMES
25622c5bff24        nginx:latest        "/docker-entrypoint.…"   6 minutes ago       Exited (137) About a minute ago                       infallible_thompson
e7ae58242760        nginx:latest        "/docker-entrypoint.…"   14 minutes ago      Exited (0) 7 minutes ago                              musing_saha
e2caa3f5f338        nginx:latest        "/docker-entrypoint.…"   17 minutes ago      Exited (0) 8 minutes ago                              y1
[root@vm1 ~]# docker rm e2caa3f5f338
e2caa3f5f338
[root@vm1 ~]# docker rm e7ae58242760
e7ae58242760
[root@localhost ~]# docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                       PORTS               NAMES
25622c5bff24        nginx:latest        "/docker-entrypoint.…"   6 minutes ago       Exited (137) 2 minutes ago                       infallible_thompson

12.docker exec //在运行的容器中执行命令

[root@vm1 ~]# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS               NAMES
25622c5bff24        nginx:latest        "/docker-entrypoint.…"   9 minutes ago       Up 24 seconds       80/tcp              infallible_thompson
[root@vm1 ~]# docker exec -it 25622c5bff24 /bin/bash
root@25622c5bff24:/# ls
bin   docker-entrypoint.d   home   media  proc	sbin  tmp
boot  docker-entrypoint.sh  lib    mnt	  root	srv   usr

13.docker inspect //获取元数据

[root@vm1 ~]# docker inspect nginx:latest 
[
    {
        "Id": "sha256:4bb46517cac397bdb0bab6eba09b0e1f8e90ddd17cf99662997c3253531136f8",
        "RepoTags": [
            "nginx:latest"
        ],
      
            "Cmd": [
                "/bin/sh",
                "-c",
                "#(nop) ",
                "CMD [\"nginx\" \"-g\" \"daemon off;\"]"
            ],
            "ArgsEscaped": true,
            "Image": "sha256:e046ee8113f48aaab8b7326ab6aed674eead374224b513de0684c2802ed2f3b9",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": [
                "/docker-entrypoint.sh"
            ],
            "OnBuild": null,
            "Labels": {
                "maintainer": "NGINX Docker Maintainers <docker-maint@nginx.com>"
            },
            "StopSignal": "SIGTERM"
        },
                .
     
        }
        "Metadata": {
            "LastTagTime": "0001-01-01T00:00:00Z"
        }
    }
]

2.docker镜像的制作

多数情况下,我们做镜像是基于别人已存在的某个基础镜像来实现的,我们把它称为base image。比如一个纯净版的最小化的centos、ubuntu或debian。

那么这个最小化的centos镜像从何而来呢?其实这个基础镜像一般是由Docker Hub的相关维护人员,也就是Docker官方手动制作的。这个基础镜像的制作对于Docker官方的专业人员来说是非常容易的,但对于终端用户来说就不是那么容易制作的了。

Docker Hub

Docker Hub is a cloud-based registry service which allows you to link to code repositories, build your images and test them, stores manually pushed images, and links to Docker Cloud so you can deploy images to your hosts.

It provides a centralized resource for container image discovery, distribution and change management, user and team collaboration, and workflow automation throughout the development pipeline.

在这里插入图片描述
Docker Hub provides the following major features:

  • Image Repositories
    • Find and pull images from community and official libraries, and manage, push to, and pull from private images libraries to which you have access.
  • Automated Builds
    • Automatically create new images when you make changes to a source code repository.
  • Webhooks
    • A feature of Automated Builds, Webhooks let you trigger actions after a successful push to a - repository.
  • Organizations
    • Create work groups to manage access to image repositories.
  • GitHub and Bitbucket Integration
    • Add the Hub and your Docker Images to your current workflows.

docker镜像的获取

To get Docker images from a remote registry(such as your own Docker registry)and add them to your local system, use the docker pull command:

# docker pull <registry>[:<port>]/[<namespace>/]<name>:<tag>

The is a host that provides the docker-distribution service on TCP (default:5000)

Together, and identify a particular image controlled by at the registry

  • Some registries also support raw ;for those, is optional
  • When it is included, however, the additional level of hierarchy that provides is usefull to distinguish between images with the same

The additional level of hierarchy of

NamespaceExample(snamespace>/<name)
organizationredhat/kubernetes, google/kubernetes
login(username)Alice/application, bob/application
roledevel/database, test/database, prod/database

镜像的生成

镜像的生成途径:

  • Dockerfile
  • 基于容器制作
  • Docker Hub automated builds

在这里插入图片描述

基于容器制作镜像

Create a new image from container’s changes

Usage:

docker commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]
OptionsDefaultDescription
—author, -aAuthor (e.g., “John Hannibal Smith hannibal@a-team.com”)
-c, --change listApply Dockerfile instruction to the created image
-m, --message stringCommit message
-p, --pausetruePause container during commit
[root@localhost ~]# docker pull busybox
Using default tag: latest
latest: Pulling from library/busybox
61c5ed1cbdf8: Pull complete 
Digest: sha256:4f47c01fa91355af2865ac10fef5bf6ec9c7f42ad2321377c21e844427972977
Status: Downloaded newer image for busybox:latest
docker.io/library/busybox:latest
[root@localhost ~]#  docker run -it --name b1 busybox
WARNING: IPv4 forwarding is disabled. Networking will not work.
/ # mkdir /data
/ #  echo 'test page.' > /data/index.html
/ # cat /data/index.html 
test page.
/ # 


在创建镜像时,我们不能关闭容器,必须使其处于运行状态,所以我们必须要另起一个终端,然后执行

[root@localhost ~]# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED              STATUS              PORTS               NAMES
baa7b0201b08        busybox             "sh"                About a minute ago   Up About a minute                       b1
[root@localhost ~]# docker commit -p baa7b0201b08 
sha256:8da607c67a3edf5dca308d3a187d85734db5599d6ade4799efa1c8b90a348b69
[root@localhost ~]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
<none>              <none>              8da607c67a3e        10 seconds ago      1.22MB
httpd               latest              a6ea92c35c43        3 weeks ago         166MB
busybox             latest              018c9d7b792b        4 weeks ago         1.22MB
[root@localhost ~]# docker tag 8da607c67a3e dockerlei123/b1:v0.1
[root@localhost ~]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED              SIZE
dockerlei123/b1     v0.1                8da607c67a3e        About a minute ago   1.22MB
httpd               latest              a6ea92c35c43        3 weeks ago          166MB
busybox             latest              018c9d7b792b        4 weeks ago          1.22MB



此时要注意的是,我们的仓库名叫b1,所以我们要在Docker Hub上创建一个名为b1的仓库,然后再将我们做好的镜像push上去

在这里插入图片描述
在这里插入图片描述
看到上图表示创建成功

[root@localhost ~]# 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: dockerlei123
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

//上传
[root@localhost ~]# docker push dockerlei123/b1:v0.1
The push refers to repository [docker.io/dockerlei123/b1]
99cd394fe45a: Pushed 
514c3a3e64d4: Mounted from library/busybox 
v0.1: digest: sha256:c91f817b24f91022c59a5b6f9262a0e5b10e7af662446b6bb9525c3b927253b8 size: 734


在这里插入图片描述
使用新生成的镜像创建容器

[root@localhost ~]# docker run --name t1 -it dockerlei123/b1:v0.1
WARNING: IPv4 forwarding is disabled. Networking will not work.
/ # ls
bin   dev   home  root  tmp   var
data  etc   proc  sys   usr
/ # cat /data/index.html 
test page.

由此可见,新生成的镜像中是包含了新增的内容的,但是此时有一个问题,那就是容器默认要启动的进程是什么?在这里,默认情况下是启动的sh进程,但我们是要启动一个apache站点,所以我们要在创建镜像时将容器默认启动的进程设为httpd,这样一来我们就可以通过新生成的镜像来快速构建一个简单的apache站点了。
使用docker inspect命令查看apache容器启动的默认进程是什么

[root@localhost ~]# docker inspect b1

           ],
            "Cmd": [
                "sh"
            ],
            "Image": "busybox",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": {}
        },

重新生成镜像并上传

[root@localhost ~]# docker commit -p -c 'CMD ["/bin/httpd","-f","-h","/data"]' b1 dockerlei123/b1:v0.2
sha256:67ce2ee1a9da2a6eb99b57c18f7e19407f0ad6d8bba72ae9f0bc67f6f0a277dd
[root@localhost ~]# docker push dockerlei123/b1

使用新生成的镜像创建容器

[root@localhost ~]# docker run --name b2 -d dockerlei123/b1:v0.2
WARNING: IPv4 forwarding is disabled. Networking will not work.
68c9e09a970718bc9f6b8c01da428208ef72966f4e076ba1044fa785fb13393b
[root@localhost ~]#  docker ps
CONTAINER ID        IMAGE                  COMMAND                  CREATED             STATUS              PORTS               NAMES
68c9e09a9707        dockerlei123/b1:v0.2   "/bin/httpd -f -h /d…"   10 seconds ago      Up 9 seconds                            b2
baa7b0201b08        busybox                "sh"                     18 minutes ago      Up 18 minutes                           b1

使用docker inspect命令查看t2容器启动的默认进程是什么,以及其IP地址,然后用curl命令访问该IP,看是否能访问到网页

[root@localhost ~]# docker inspect b2
  "Cmd": [
                "/bin/httpd",
                "-f",
                "-h",
                "/data"
"IPAddress": "172.17.0.3",

[root@localhost ~]# curl 172.17.0.3
test page.

镜像的导入与导出

假如有2台主机,我们在主机1上做了一个镜像,主机2想用这个镜像怎么办呢?

我们可以在主机1上push镜像到镜像仓库中,然后在主机2上pull把镜像拉下来使用,这种方式就显得比较麻烦,假如我只是测试用的,在一台主机上做好镜像后在另一台主机上跑一下就行了,没必要推到仓库上然后又把它拉到本地来。

此时我们可以在已有镜像的基础上把镜像打包成一个压缩文件,然后拷贝到另一台主机上将其导入,这就是镜像的导入和导出功能。

docker中我们使用docker save进行导出,使用docker load进行导入。

在已生成镜像的主机上执行docker save导出镜像

[root@localhost ~]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
dockerlei123/b1     v0.2                67ce2ee1a9da        6 minutes ago       1.22MB
dockerlei123/b1     v0.1                8da607c67a3e        20 minutes ago      1.22MB
httpd               latest              a6ea92c35c43        3 weeks ago         166MB
busybox             latest              018c9d7b792b        4 weeks ago         1.22MB
[root@localhost ~]#  docker save -o httpd dockerlei123/b1
[root@localhost ~]# ls
anaconda-ks.cfg  httpd

执行docker load导入镜像

[root@localhost ~]#  docker load -i /root/httpd
Loaded image: dockerlei123/b1:v0.1
Loaded image: dockerlei123/b1:v0.2

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值