前言

Docker简介

Docker 是一个开源的应用容器引擎 , 基于GO语言并遵从Apache2.0 协议开源 。 Docker可以让开发者打包他们的应用的以及依赖包到一个轻量级 、 可移植性高的容器中 。 然后发布到任何流行的Linux 机器上 , 可以实现虚拟化 。

安装和简单的配置

  • 在ubuntu环境中安装docker社区版

$ sudo apt install docker-ce

  • 查看docker的版本号

docker version

Client:
Version: 18.06.1-ce
API version: 1.38
Go version: go1.10.3
Git commit: e68fc7a
Built: Tue Aug 21 17:25:03 2018
OS/Arch: linux/amd64
Experimental: false

  • 镜像加速配置

国内访问很多国外的资料可能被qiang,或者速度不是很理想,所以这里改为阿里云镜像加速器。点击这个链接,然后把图中的URL复制。
docker 简单教程
按照这个格式复制到/etc/docker/deamon.json,如果没有就新建。

{    
    "registry-mirrors": ["https://xxxxxxxxx.mirror.aliyuncs.com"]                                                           
}  

然后重启docker

sudo systemctl daemon-reload
sudo systemctl restart docker
  • helloworld
    接着使用docker运行第一个hello world
$ sudo docker run hello-world

运行结果,没有异常的话说明docker安装成功。

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/engine/userguide/

正文

基本操作

详解命令sudo docker run ubuntu hello world

sudo docker run ubuntu echo hello world
hello world

docker 允许你在容器内运行应用程序 , 使用docker run 命令来在ubuntu容器内运行一个应用程序 并输出hello world。
命令详解:

docker : docker 的二进制可执行文件。 文件位于/usr/bin/docker
run : docker 的 执行参数, 作用是执行容器中的镜像
echo : 在镜像中执行的命令

上面的命令的完整解释是:在docker中运行ubuntu镜像,并且在ubuntu中执行echo hello world这条命令。最后将运行结果打印到物理机的终端上。

docker 运行交互式容器

在上面的一条命令中,我们启动的容器没有交互能力,如果需要交互,需要添加参数-t -i

sudo docker run -t -i ubuntu

或者是指定shell运行

sudo docker run -t -i ubuntu /bin/bash

docker 简单教程
退出绘画模式可以使用命令exit或者Ctrl+d

docker后台模式

后台运行容器的话,需要添加参数-d,可以使用命令sudo docker ps查看后台正在运行的进程。

$ sudo docker run -d ubuntu /bin/sh -c "while true;do echo hello;sleep 1;done;"
a84bdb35787ab848d2aa4e3d32902ec33d50cb88790b3d9670ceb47acd7ff18b

$ sudo docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS               NAMES
a84bdb35787a        ubuntu              "/bin/sh -c 'while t…"   20 seconds ago      Up 17 seconds                           xenodochial_goldwasser

查看进程日志使用sudo docker logs 镜像进程id

$ sudo docker logs a84b
hello
hello
hello
hello
hello
hello
...

停止容器可以使用命令sudo docker stop (镜像进程id|NAMES)

$ sudo docker stop a84b
a84b

$ sudo docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES

docker help

查看所有可用的命令docker或者docker --help

$ sudo docker

Usage:	docker [OPTIONS] COMMAND

A self-sufficient runtime for containers

Options:
      --config string      Location of client config files (default "/home/wqm/.docker")
  -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 "/home/wqm/.docker/ca.pem")
      --tlscert string     Path to TLS certificate file (default "/home/wqm/.docker/cert.pem")
      --tlskey string      Path to TLS key file (default "/home/wqm/.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
  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.

查看某一命令的帮助:docker COMMAND --help

$ sudo docker ps --help

Usage:	docker ps [OPTIONS]

List containers

Options:
  -a, --all             Show all containers (default shows just running)
  -f, --filter filter   Filter output based on conditions provided
      --format string   Pretty-print containers using a Go template
  -n, --last int        Show n last created containers (includes all states) (default -1)
  -l, --latest          Show the latest created container (includes all states)
      --no-trunc        Don't truncate output
  -q, --quiet           Only display numeric IDs
  -s, --size            Display total file sizes

拉取网络仓库的镜像

下载网络仓库上的镜像可以使用sudo docker pull imageName

# python Flask
sudo docker pull training/webapp
Using default tag: latest
latest: Pulling from training/webapp
e190868d63f8: Pull complete 
909cd34c6fd7: Pull complete 
0b9bfabab7c1: Pull complete 
a3ed95caeb02: Pull complete 
10bbbc0fc0ff: Pull complete 

运行刚刚下载的镜像

sudo docker run -P training/webapp python app.py
* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)

+172.17.0.1 - - [22/Oct/2018 05:37:59] "GET / HTTP/1.1" 200 -

其中的参数-P,docker随机映射一个真实的端口到内部容器开放的网络端口,如果需要需要指定端口需要到参数-p 外部端口:容器网络端口

外部真实端口可以使用docker ps查看或者docker port id|names

$ sudo docker ps 
[sudo] wqm 的密码: 
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                     NAMES
d087f0af8a22        training/webapp     "python app.py --help"   33 seconds ago      Up 30 seconds       0.0.0.0:32770->5000/tcp   happy_fermi
sudo docker port 8145deb0c85a
5000/tcp -> 0.0.0.0:5553

如果是后台运行,可以使用这个命令来查看日志sudo docker logs -f id|names,参数-f的效果和linux的命令tail -f类似。

sudo docker logs -f 8145deb0c85a 
 * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
172.17.0.1 - - [22/Oct/2018 05:44:49] "GET / HTTP/1.1" 200 -

查看详细的信息

需要查看正在运行的镜像的详细信息的话,需要使用docerk inspect id|names

sudo docker inspect 5b0b71d6021a
[
    {
        "Id": "5b0b71d6021a4427180f11ef8da0f80781041d5637d43e3a0f0eadf4164e453e",
        "Created": "2018-10-22T05:44:07.581398282Z",
        "Path": "python",
        "Args": [
            "app.py",
            "--help"
        ],
        "State": {
            "Status": "exited",
            "Running": false,
            ....

容器中镜像的操作

停止: docker stop id|names
启动|重启 :docker start id|names
删除:docker rm id|names

镜像相关

列出本地所有的镜像

$ sudo docker images
REPOSITORY                                 TAG                 IMAGE ID            CREATED             SIZE
deploy_xjmeishi                            latest              355ab8fbf7c8        4 months ago        994MB
ubuntu                                     latest              452a96d81c30        5 months ago        79.6MB

标签说明

REPOSITORY : 镜像的仓库源
TAG : 镜像的标签,同一个镜像不同的TAG代表镜像的不同的版本,指定运行的镜像版本REPOSITORY:TAG
IMAGE ID : 镜像ID
CREATED : 镜像创建的时间
SIZE : 镜像的大小

当运行(run)本地不存在的镜像时,docker会自动拉取(pull)资源,一般先通过docker pull获取镜像后再执行docker run

查找镜像

  • 可以通过在线网站查找,这个网站
    docker 简单教程
  • 或者使用命令docker search
$ sudo docker search ubuntu
NAME                                                   DESCRIPTION                                     STARS               OFFICIAL            AUTOMATED
ubuntu                                                 Ubuntu is a Debian-based Linux operating sys…   8580                [OK]                
dorowu/ubuntu-desktop-lxde-vnc                         Ubuntu with openssh-server and NoVNC            230                                     [OK]
rastasheep/ubuntu-sshd                                 Dockerized SSH service, built on top of offi…   176                                     [OK]
consol/ubuntu-xfce-vnc                                 Ubuntu container with "headless" VNC session…   129    
....

标签说明:

NAME:镜像名字
DESCRIPTION:镜像描述
START:类似点赞数,默认以这个排序
OFFICIAL:是否是官方镜像
AUTOMATED:是否自动化部署

拉取(下载)镜像

前面已经使用过,所以这里略过。

sudo docker pull name

更新镜像

在运行的应用中执行apt-get update,或者执行其他的修改步骤。

[email protected]:/# apt-get update
Get:1 http://archive.ubuntu.com/ubuntu bionic InRelease [242 kB]           
Get:2 http://security.ubuntu.com/ubuntu bionic-security InRelease [83.2 kB]
Get:3 http://archive.ubuntu.com/ubuntu bionic-updates InRelease [88.7 kB]     
....

在应用中更新之后,使用 docker commit对应用的更新进行提交。

$ sudo docker commit -m="update something 10/22" -a="jedi" ebb8217a4752 jedi/ubuntu_v2
sha256:ac9f4b80139283ac5deeb94858d3510dc0f377043f992df219444a9c99cff16b

参数说明

commit : 提交更新命令
-m : 提交更新的信息,不填的话很难辨认的好吗
-a : 镜像的作者
jedi/ubuntu_v2 : 创建镜像的名字

提交成功之后,使用命令docker images可以看到刚刚创建的镜像。

$ sudo docker images
REPOSITORY                                 TAG                 IMAGE ID            CREATED             SIZE
jedi/ubuntu_v2                             latest              ac9f4b801392        5 minutes ago       122MB
deploy_xjmeishi                            latest              355ab8fbf7c8        4 months ago        994MB
....

docker 实例

安装mysql

首先安装mysql

sudo docker pull mysql

接着启动mysql

sudo docker run -p 3333:3306 -v $PWD/conf:/etc/mysql/config.d -v $PWD/logs:/logs -v $PWD/data:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=123456 --name mysql_1 mysql

参数说明

-p 3333:3306内部容器的3306端口映射到本机的3333端口
-v $PWD/conf:/etc/mysql/config.d : 将本机当前目录下的/conf目录映射到容器的/etc/mysql/config.d
-e MYSQL_ROOT_PASSWORD=123456 : 传递环境变量到容器内部。这里是初始化mysql密码
-name mysql_1 mysql : 指定容器名字

后言

共勉。

相关文章: