初探docker(一) | docker的安装及常见命令

本文介绍的是docker的安装及常见命令。

摘要:Docker 是个划时代的开源项目,它彻底释放了计算虚拟化的威力,极大提高了应用的维护效率,降低了云计算应用开发的成本。使用 Docker,可以让应用的部署、测试和分发都变得前所未有的高效和轻松。

关键词:Docker

安装Docker

参考:https://mirror.nju.edu.cn/mirrorz-help/docker-ce/?mirror=NJU

1
2
3
4
5
export DOWNLOAD_URL="https://mirrors.ustc.edu.cn/docker-ce"
# 如您使用 curl
curl -fsSL https://get.docker.com/ | sudo -E sh
# 如您使用 wget
wget -O- https://get.docker.com/ | sudo -E sh

启动Docker-CE

1
2
sudo systemctl enable docker
sudo systemctl start docker

解决docker info产生的Warning

1
2
3
4
5
6
7
8
#WARNING: bridge-nf-call-iptables is disabled
#WARNING: bridge-nf-call-ip6tables is disabled

cat <<EOF | sudo tee /etc/sysctl.d/docker.conf
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1
EOF
sudo sysctl --system

优雅的删除docker

Debian系:

1
dpkg -l | grep docker
1
sudo apt remove --purge docker-ce docker-ce-cli
1
rm -rf /var/lib/docker

测试 Docker 是否安装正确

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
docker run hello-world
以下是输出:
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
d1725b59e92d: Pull complete
Digest: sha256:0add3ace90ecb4adbf7777e9aacf18357296e799f81cabc9fde470971e499788
Status: Downloaded newer image for hello-world:latest

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/get-started/

获取镜像加速器

国内从 Docker Hub 拉取镜像有时会遇到困难,此时可以配置镜像加速器。国内很多云服务商都提供了国内加速器服务,例如:

- 网易云加速器 https://hub-mirror.c.163.com

- 百度云加速器 https://mirror.baidubce.com

- 阿里云加速器(需登录账号获取)

- DaoCloud

执行以下命令即可:

1
curl -sSL https://get.daocloud.io/daotools/set_mirror.sh | sh -s http://f1361db2.m.daocloud.io

Linux

这里使用国内南京大学提供的镜像缓存服务:

参考: https://nju-mirror-help.njuer.org/dockerhub.html https://sci.nju.edu.cn/9e/05/c30384a564741/page.htm

对于使用 systemd 的系统,请在 /etc/docker/daemon.json 中写入如下内容(如果文件不存在请新建该文件):

1
2
3
{
registry-mirrors: [https://docker.nju.edu.cn/]
}

注意要保证该文件符合 json 规范,否则 Docker 将不能启动。

之后重启服务。

1
2
sudo systemctl daemon-reload
sudo systemctl restart docker

Windows 10

对于使用 Windows 10 的用户,在任务栏托盘 Docker 图标内右键菜单选择 Settings,打开配置窗口后在左侧导航菜单选择 Docker Engine,在右侧像下边一样编辑 json 文件,之后点击 Apply & Restart 保存后 Docker 就会重启并应用配置的镜像地址了。

1
2
3
4
5
6
7
8
{
"registry-mirrors": [
"https://docker.nju.edu.cn/"
],
"insecure-registries": [],
"debug": true,
"experimental": false
}

常见docker命令

取回容器

1
docker pull fly97/v2fly

运行容器

1
docker run -d --name v2fly -v /etc/caddy:/etc/caddy  -p 443:443 fly97/v2fly

-v :启用目录挂载。冒号":"前面的目录是宿主机目录,后面的目录是容器内目录

-p:启用端口映射。

-d:在后台运行容器并打印容器ID。

--restart=always:保证每次docker服务重启后容器也自动重启

--network

​ 如果容器已经启动了而又想设置容器自动启动:

1
docker update --restart=always <CONTAINER ID/CONTAINER NAME>

进入容器

1
docker exec -it $(docker ps| grep fly97/v2fly | awk '{print $1}' /bin/sh

-i: 交互式操作。

-t:启用终端运行。

/bin/sh:打开交互式 Shell

查看当前运行的容器

1
docker ps 

运行容器

1
docker start CONTAINER_NAME

停止容器

1
docker stop CONTAINER_NAME

删除容器

1
docker rm CONTAINER_NAME

查看镜像

1
docker images

删除镜像

1
docker rmi IMAGE_ID

清理镜像

1
docker image prune

全部命令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
PS C:\Users\wf09\Desktop\v2fly-docker> docker --help

Usage: docker [OPTIONS] COMMAND

A self-sufficient runtime for containers

Options:
--config string Location of client config files (default
"C:\\Users\\wf09\\.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
"C:\\Users\\wf09\\.docker\\ca.pem")
--tlscert string Path to TLS certificate file (default
"C:\\Users\\wf09\\.docker\\cert.pem")
--tlskey string Path to TLS key file (default
"C:\\Users\\wf09\\.docker\\key.pem")
--tlsverify Use TLS and verify the remote
-v, --version Print version information and quit

Management Commands:
builder Manage builds
config Manage Docker configs
container Manage containers
context Manage contexts
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使用sudo的问题

创建docker组

1
sudo groupadd docker

将当前用户加入docker组

1
sudo gpasswd -a ${USER} docker

重启服务

1
sudo service docker restart

刷新docker组成员

1
newgrp - docker

构建Docker镜像时处理'Configuring tzdata'交互输入

将tzdata设置为非交互方式

1
ENV DEBIAN_FRONTEND=noninteractive

docker容器内使用dpkg安装chrome浏览器失败

使用apt离线安装即可,会自动帮你安装依赖

1
2
wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
apt install -f ./google-chrome-stable_current_amd64.deb

docker 访问外部 https 的数字证书验证问题

  1. alpine linux

    1
    2
    RUN apk --no-cache add ca-certificates \
    && update-ca-certificates
  2. ubuntu linux

    1
    2
    RUN apt-get install ca-certificates -y \
    && update-ca-certificates

修改docker时区

  1. 挂载宿主机时区文件 到容器内/etc/localtime

    1
    - /usr/share/zoneinfo/Asia/Shanghai:/etc/localtime
  2. debian类镜像构建时指定环境变量

    1. 容器安装tzdata
    1
    RUN apt-get install -f tzdata
    1. 使用对应时区的环境变量
    1
    ENV TZ="Asia/Shanghai"

docker inspect命令

查看容器状态

首先运行docker inspect查看容器信息

可以获取以下容器状态

查看容器是否正常运行
1
docker inspect --format '{{.State.Status}}' summary
查看容器是否正在重启
1
docker inspect --format '{{.State.Restarting}}' summary

查看容器日志存放路径

某些情况下需要删除日志文件路径,因此可以通过这个命令查看。查看定义日志的字段:

运行以下命令获取日志的地址

1
docker inspect --format '{{.LogPath}}' summary

然后在操作就好了

设置容器日志大小

一般情况下Docker容器业务日志很大,处理起来不是很方便

指定容器

docker-compose

1
2
3
4
5
6
7
services:
summary:
logging:
driver: "json-file" # 日志驱动
options:
max-size: "50m" #[0-9+][k|m|g] 【文件的大小】
max-file: "3" #[0-9+] 【文件数量】

docker cli

1
2
3
--log-driver json-file            #日志驱动
--log-opt max-size=[0-9+][k|m|g] #文件的大小
--log-opt max-file=[0-9+] #文件数量

全局设置

编辑文件/etc/docker/daemon.json,增加以下日志的配置

1
2
3
4
5
6
7
{
"log-driver":"json-file",
"log-opts":{
"max-size":"500m",
"max-file":"3"
}
}

手动安装Docker

指定私有仓库的方式安装Docker

安装curl

1
sudo apt install curl -y
1
2
3
4
5
sudo mkdir -p /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg
echo \
"deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://repo.deepsoft-tech.com/repository/docker-apt \
$(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null

安装docker-ce

1
2
sudo apt-get update
sudo apt-get install docker-ce docker-ce-cli containerd.io docker-compose-plugin -y