docker快速入门

时间:2022-05-11
本文章向大家介绍docker快速入门,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

docker已经是一年前的时候学习的了,当时,不会go语言。工作中一直没有使用,已经忘光了。在放假前,sdk那边说线上docker的打包环境每次打包特别慢,查询了一下,每次打包都会下载所有需要的依赖。重复下载,需要优化到下载完成后的状态。放假期间一直在复习python的科学计算和golang。就没有花时间在docker上。 我今天的高铁回广州,提前到了,在淘宝上花了0.3元,买了一个cmcc-web账号,联网。学习学习docker简单使用。

Docker 是什么?

Docker 是一个开源的容器引擎,而一个容器其实是一个虚拟化的独立的环境,因此开发者可以将应用打包到这样的一个 docker 容器中,然后发布到任何可以运行 docker 容器的机器中,实现一次打包多处部署,解决了因为环境问题而导致的部署难题。

Docker是一个开源的引擎,可以轻松的为任何应用创建一个轻量级的、可移植的、自给自足的容器。开发者在笔记本上编译测试通过的容器可以批量地在生产环境中部署,包括VMs(虚拟机)、bare metal、OpenStack 集群和其他的基础应用平台。 Docker通常用于如下场景:

  • web应用的自动化打包和发布;
  • 自动化测试和持续集成、发布;
  • 在服务型环境中部署和调整数据库或其他的后台应用;
  • 从头编译或者扩展现有的OpenShift或Cloud Foundry平台来搭建自己的PaaS环境。

容器是什么?

与 容器 对应的一个概念就是 镜像,镜像可以看做我们平时装系统的镜像,里面就是一个运行环境。当然我比较喜欢将镜像比作一个我们面向对象编程中的 类,而一个容器就是一个类的 实例,因此可以根据一个镜像,创建出很多个容器。每一个容器都是具体的,我们可以在容器上面做出更改,然后再把这个容器打包成一个新的镜像,从而以后可以根据改动后的镜像创建出新的容器。而容器本身可以简单理解为是一个虚拟独立的运行环境,我们要做的是中这个环境中打包我们的应用,以便于再次部署。

安装 Docker

MAC

brew isntall docker

Ubuntu

sudo apt-get install docker-ce

启动 docker 守护进程

brew services docker start

Ubuntu

systemctl start docker
service docker start

docker 命令介绍

ubuntu@youdi  /etc/init.d  docker --help                                                                                                

Usage:  docker COMMAND

A self-sufficient runtime for containers

Options:
      --config string      Location of client config files (default "/home/ubuntu/.docker")
  -D, --debug              Enable debug mode
      --help               Print usage
  -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 "/home/ubuntu/.docker/ca.pem")
      --tlscert string     Path to TLS certificate file (default "/home/ubuntu/.docker/cert.pem")
      --tlskey string      Path to TLS key file (default "/home/ubuntu/.docker/key.pem")
      --tlsverify          Use TLS and verify the remote
  -v, --version            Print version information and quit

Management Commands:
  config      Manage Docker configs
  container   Manage containers
  image       Manage images
  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
  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.



# docker --help
管理命令:
  container   管理容器
  image       管理镜像
  network     管理网络
命令:
  attach      介入到一个正在运行的容器
  build       根据 Dockerfile 构建一个镜像
  commit      根据容器的更改创建一个新的镜像
  cp          在本地文件系统与容器中复制 文件/文件夹
  create      创建一个新容器
  exec        在容器中执行一条命令
  images      列出镜像
  kill        杀死一个或多个正在运行的容器    
  logs        取得容器的日志
  pause       暂停一个或多个容器的所有进程
  ps          列出所有容器
  pull        拉取一个镜像或仓库到 registry
  push        推送一个镜像或仓库到 registry
  rename      重命名一个容器
  restart     重新启动一个或多个容器
  rm          删除一个或多个容器
  rmi         删除一个或多个镜像
  run         在一个新的容器中执行一条命令
  search      在 Docker Hub 中搜索镜像
  start       启动一个或多个已经停止运行的容器
  stats       显示一个容器的实时资源占用
  stop        停止一个或多个正在运行的容器
  tag         为镜像创建一个新的标签
  top         显示一个容器内的所有进程
  unpause     恢复一个或多个容器内所有被暂停的进程

在子命令中还有更多丰富的选项,可以使用 docker COMMAND --help 查看。例如:

docker run --help

docker 使用实战

接下来,我将利用 docker 部署一个 Nginx 服务器,作为讲解的例子。 要创建一个容器,那么我们必须先要有一个用于创建容器的镜像。 在 docker hub 中查找 nginx 相关镜像。

# docker search nginx
 ubuntu@youdi  /etc/init.d  docker search nginx                                                                                                                                                                    
NAME                                                   DESCRIPTION                                     STARS               OFFICIAL            AUTOMATED
nginx                                                  Official build of Nginx.                        6979                [OK]                
jwilder/nginx-proxy                                    Automated Nginx reverse proxy for docker c...   1136                                    [OK]
richarvey/nginx-php-fpm                                Container running Nginx + PHP-FPM capable ...   453                                     [OK]
jrcs/letsencrypt-nginx-proxy-companion                 LetsEncrypt container to use with nginx as...   229                                     [OK]
kong                                                   Open-source Microservice & API Management ...   116                 [OK]                
webdevops/php-nginx                                    Nginx with PHP-FPM                              90                                      [OK]

...
...

拉取官方镜像,其中上面的非官方镜像是用户们根据自己的需要制作的镜像,方便大家的使用。

# docker pull nginx
 ubuntu@youdi  /etc/init.d  docker pull nginx                                                                                                                                                                      
Using default tag: latest
latest: Pulling from library/nginx
afeb2bfd31c0: Pull complete                                                                                                                                                                                          
7ff5d10493db: Pull complete                                                                                                                                                                                          
d2562f1ae1d0: Pull complete                                                                                                                                                                                          
Digest: sha256:af32e714a9cc3157157374e68c818b05ebe9e0737aac06b55a09da374209a8f9
Status: Downloaded newer image for nginx:latest

在这里顺便说一下,docker 镜像是分层存储的,所以上面的 nginx 镜像有 3 层,另外每根据新的容器制作一个新的镜像以后会给这个镜像加上一层。

接下来直接利用这个镜像启动一个新的容器:

 ubuntu@youdi  /etc/init.d  docker run --name youdi-nginx -d -p 8080:80 nginx                                                                                                                                    
491435cc907a64392d4bed79fa454ea5ce0ae48ee6719f1a0da86f5c679dd6aa

此时中浏览器中输入:http://localhost:8080/ 即可访问 nginx。 参数解释:

 ubuntu@youdi  /etc/init.d  curl http://localhost:8080
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>

--name 为容器取一个名字 -p 参数语法为 -p host port:container port; -p 8080:80 将主机上的8080端口绑定到容器上的80端口,因此在主机中访问8080端口时其实就是访问 nginx 容器的80端口 -d 后台运行容器 然后我们来看一个更复杂的例子:

# docker run --name youdi-nginx  
    -v /host/path/nginx.conf:/etc/nginx/nginx.conf:ro 
    -v /some/html:/usr/share/nginx/html:ro 
    -p 8080:80 
    -d nginx

这个例子多了一个参数-v,这个参数的作用是把本地的文件或者文件夹挂载到容器中,其中最后面的 ro 或者 rw 控制这个挂载是否可写。

-v 参数语法为-v host dir:container dir[:ro|rw] 上面的命令将本地文件中的 nginx.conf 配置文件挂载到容器,并且将要展示的静态页面也挂载到容器。 注意:在容器执行一条命令以后,当这个命令结束运行,容器也会结束运行。

接下来让我们看看 docker 别的命令。

查看所有运行中的容器:

# docker ps
</html>
 ubuntu@youdi  /etc/init.d  docker ps                                                                                                                                                                              
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                  NAMES
491435cc907a        nginx               "nginx -g 'daemon ..."   4 minutes ago       Up 4 minutes        0.0.0.0:8080->80/tcp   youdi-nginx
# docker ps -a ### 列出包括未运行的容器
查看容器运行日志:
```bash
# docker logs youdi-nginx
 ubuntu@youdi  /etc/init.d  docker logs youdi-nginx                                                                                                                                                                
172.17.0.1 - - [08/Oct/2017:10:42:26 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.47.0" "-"

重启容器:

# docker restart youdi-nginx
youdi-nginx

停止运行一个容器:

# docker stop youdi-nginx
youdi-nginx
# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED  STATUS              PORTS               NAMES

启动一个已经存在的容器:

# docker start youdi-nginx
youdi-nginx
# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                  NAMES
491435cc907a        nginx               "nginx -g 'daemon ..."   7 minutes ago       Up 15 seconds       0.0.0.0:8080->80/tcp   youdi-nginx

直接杀死一个运行中的容器:

# docker kill youdi-nginx

重命名容器:

# docker rename youdi-nginx liangchangyou-nginx 

删除容器:

# docker rm liangchangyou-nginx

查看本机所有镜像:

# docker imags
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
nginx               latest              da5939581ac8        3 weeks ago         108MB

使用已经存在的容器创建一个镜像:

# docker commit -m "nothing changed" youdi-nginx youdi-nginx-image
ha256:78cf8a11778f4b8bdb5dd9fbb92d621854efdf37fcb9ea246c888c7d77fc463e
# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
youdi-nginx-image   latest              78cf8a11778f        27 seconds ago      108MB
nginx               latest              da5939581ac8        3 weeks ago         108MB

使用我们自己创建的镜像创建容器:

# docker run --name test -d -p 8081:80 youdi-nginx-image
dc399ca6c79d952d23f4145eaec3b43e98c0aaeb0e289a5989bf0b1b596e3e15
# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                  NAMES
dc399ca6c79d        youdi-nginx-image   "nginx -g 'daemon ..."   3 minutes ago       Up 3 minutes        0.0.0.0:8081->80/tcp   test
50588da5b273        nginx               "nginx -g 'daemon ..."   2 hours ago         Up 2 hours          0.0.0.0:8080->80/tcp   youdi-nginx

如果我们使用的容器的启动命令是一个 shell ,那么我们可以使用 attach 命令来介入这个容器,就跟我们使用 ssh 连接一台服务器差不多。

# docker attach some-container

在创建一个容器时直接启动一个可交互式的 shell, 并且退出后自动删除容器:

# docker run -it --rm  centos

本文介绍了 docker 的简单用法,同时也给出了一个实际的例子用来展示 docker 命令的各种操作。作为一个快速入门的文章,本文写的相对有点简单,很多概念上的东西还需要求查看别的资料理解,但是看完本文应该就具备使用 docker 的基本能力了。此外,后续的文章应该会写一点 Dockerfile 与 docker-compose 相关的内容。