03-安装docker-compose及必要应用

docker环境

安装docker 社区版

在线安装

1
2
3
4
5
6
yum install -y yum-utils
yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
yum install docker-ce docker-ce-cli containerd.io

systemctl start docker
docker run hello-world

离线安装docker

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
### 下载二进制docker(离线内网安装)
mkdir -p /data/pkg/
cd /data/pkg/
wget https://download.docker.com/linux/static/stable/x86_64/docker-20.10.9.tgz
### 创建属组docker
groupadd docker
### 创建docker用户 加入docker组
useradd -m -g docker -d /data/docker docker
### 如果没有加入docker组 可以手工加入docker组
gpasswd -a docker docker
### 安装docker
cd /data/app/
tar zxvf /data/pkg/docker-20.10.9.tgz
### 配置环境变量
export PATH=${PATH}:/data/app/docker
### 启动docker
nohup /data/app/docker/dockerd &
1
2
### 复制到默认的PATH目录下  有可能有报错,缺少什么就复制什么.
cp /data/app/docker/dockerd /data/app/docker/containerd /data/app/docker/docker /data/app/docker/runc /data/app/docker/containerd-shim-runc-v2 /usr/bin/

编辑systemctrl托管文件

/usr/lib/systemd/system/containerd.service

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
# Copyright The containerd Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

[Unit]
Description=containerd container runtime
Documentation=https://containerd.io
After=network.target local-fs.target

[Service]
ExecStartPre=-/sbin/modprobe overlay
ExecStart=/usr/bin/containerd

Type=notify
Delegate=yes
KillMode=process
Restart=always
RestartSec=5
# Having non-zero Limit*s causes performance problems due to accounting overhead
# in the kernel. We recommend using cgroups to do container-local accounting.
LimitNPROC=infinity
LimitCORE=infinity
LimitNOFILE=infinity
# Comment TasksMax if your systemd version does not supports it.
# Only systemd 226 and above support this version.
TasksMax=infinity
OOMScoreAdjust=-999

[Install]
WantedBy=multi-user.target

/usr/lib/systemd/system/docker.service

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
[Unit]
Description=Docker Application Container Engine
Documentation=https://docs.docker.com
After=network-online.target docker.socket firewalld.service containerd.service time-set.target
Wants=network-online.target containerd.service
Requires=docker.socket

[Service]
Type=notify
# the default is not to use systemd for cgroups because the delegate issues still
# exists and systemd currently does not support the cgroup feature set required
# for containers run by docker
ExecStart=/usr/bin/dockerd --data-root /data/docker -H fd:// --containerd=/run/containerd/containerd.sock
ExecReload=/bin/kill -s HUP $MAINPID
TimeoutStartSec=0
RestartSec=2
Restart=always

# Note that StartLimit* options were moved from "Service" to "Unit" in systemd 229.
# Both the old, and new location are accepted by systemd 229 and up, so using the old location
# to make them work for either version of systemd.
StartLimitBurst=3

# Note that StartLimitInterval was renamed to StartLimitIntervalSec in systemd 230.
# Both the old, and new name are accepted by systemd 230 and up, so using the old name to make
# this option work for either version of systemd.
StartLimitInterval=60s

# Having non-zero Limit*s causes performance problems due to accounting overhead
# in the kernel. We recommend using cgroups to do container-local accounting.
LimitNOFILE=infinity
LimitNPROC=infinity
LimitCORE=infinity

# Comment TasksMax if your systemd version does not support it.
# Only systemd 226 and above support this option.
TasksMax=infinity

# set delegate yes so that systemd does not reset the cgroups of docker containers
Delegate=yes

# kill only the docker process, not all processes in the cgroup
KillMode=process
OOMScoreAdjust=-500

[Install]
WantedBy=multi-user.target

/usr/lib/systemd/system/docker.socket

1
2
3
4
5
6
7
8
9
10
11
12
13
[Unit]
Description=Docker Socket for the API

[Socket]
# If /var/run is not implemented as a symlink to /run, you may need to
# specify ListenStream=/var/run/docker.sock instead.
ListenStream=/run/docker.sock
SocketMode=0660
SocketUser=root
SocketGroup=docker

[Install]
WantedBy=sockets.target
  • 套接字通信测试小实验
    1
    2
    3
    4
    5
    6
    7
    8
    yum install -y nc
    # 监听套接字文件
    ncat -l -U /var/run/docker.sock-test
    在这里输出信息

    # 输出到套接字文件
    nc -U /var/run/docker.sock-test
    在这里输入信息
1
2
3
4
5
6
7
8
9
10
### 配置服务
systemctl daemon-reload
systemctl start containerd
systemctl start docker
systemctl enable docker


### 测试 (非root也可以)
su - dock
docker run hello-world

hello-world 测试成功

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
[root@lqz-test-demo docker]# docker run hello-world
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
c1ec31eb5944: Pull complete
Digest: sha256:d000bc569937abbe195e20322a0bde6b2922d805332fd6d8a68b19f524b7d21d
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/

[root@lqz-test-demo docker]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
[root@lqz-test-demo docker]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
032728d558f6 hello-world "/hello" 10 seconds ago Exited (0) 9 seconds ago jolly_agnesi
[root@lqz-test-demo docker]#

  • 可能出现的错误

    1
    2
    time="2024-03-04T20:19:19.229005631+08:00" level=warning msg="could not change group /var/run/docker.sock to docker: group docker not found"
    failed to start containerd: exec: "containerd": executable file not found in $PATH
    1
    2
    3
    4
    5
    6
    7
    Digest: sha256:d000bc569937abbe195e20322a0bde6b2922d805332fd6d8a68b19f524b7d21d
    Status: Downloaded newer image for hello-world:latest
    docker: Error response from daemon: runtime "io.containerd.runc.v2" binary not installed "containerd-shim-runc-v2": file does not exist: unknown.
    ERRO[0008] error waiting for container: context canceled
    [root@lqz-test-demo ~]# docker run hello-world
    docker: Error response from daemon: runtime "io.containerd.runc.v2" binary not installed "containerd-shim-runc-v2": file does not exist: unknown.

    1
    2
    3
    4
    5
    6
    7
    8
    3月 05 23:41:16 lqz-test-demo dockerd[3516]: time="2024-03-05T23:41:16.021871261+08:00" level=warning msg="failed to retrieve docker-init version: exec: \"docker-init\": executable file not found in $PATH"
    3月 05 23:41:16 lqz-test-demo dockerd[3516]: time="2024-03-05T23:41:16.023921698+08:00" level=info msg="Docker daemon" commit=79ea9d3 graphdriver(s)=overlay2 version=20.10.9
    3月 05 23:41:16 lqz-test-demo dockerd[3516]: time="2024-03-05T23:41:16.023947949+08:00" level=info msg="Daemon has completed initialization"
    3月 05 23:41:16 lqz-test-demo dockerd[3516]: failed to find runc binary
    3月 05 23:41:16 lqz-test-demo systemd[1]: docker.service: main process exited, code=exited, status=1/FAILURE
    3月 05 23:41:16 lqz-test-demo systemd[1]: Failed to start Docker Application Container Engine.
    -- Subject: Unit docker.service has failed

  • 常用命令参数-官网

    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
    88
    89
    90
    91
    92
    93
    Usage: dockerd [OPTIONS]

    A self-sufficient runtime for containers.

    Options:
    --add-runtime runtime Register an additional OCI compatible runtime (default []) : 注册额外的OCI兼容运行时(默认[])
    --allow-nondistributable-artifacts list Allow push of nondistributable artifacts to registry : 允许将不可分发的项目推送到注册表
    --api-cors-header string Set CORS headers in the Engine API : 在引擎API中设置CORS头
    --authorization-plugin list Authorization plugins to load : 要加载的授权插件
    --bip string Specify network bridge IP : 指定网桥IP
    -b, --bridge string Attach containers to a network bridge : 将容器连接到网桥
    --cdi-spec-dir list CDI specification directories to use : 要使用的CDI规范目录
    --cgroup-parent string Set parent cgroup for all containers : 为所有容器设置父组
    --config-file string Daemon configuration file (default "/etc/docker/daemon.json") : 守护程序配置文件(默认为“/etc/docker/Daemon.json”)
    --containerd string containerd grpc address : containerd grpc地址
    --containerd-namespace string Containerd namespace to use (default "moby") : 要使用的Container命名空间(默认为“moby”)
    --containerd-plugins-namespace string Containerd namespace to use for plugins (default "plugins.moby") : 包含用于插件的命名空间(默认为“plugins.moby”)
    --cpu-rt-period int Limit the CPU real-time period in microseconds for the : 将的CPU实时周期限制为微秒
    parent cgroup for all containers (not supported with cgroups v2) : 所有容器的父cgroup(cgroups v2不支持)
    --cpu-rt-runtime int Limit the CPU real-time runtime in microseconds for the : 将的CPU实时运行时间限制为微秒
    parent cgroup for all containers (not supported with cgroups v2) : 所有容器的父cgroup(cgroups v2不支持)
    --cri-containerd start containerd with cri : 用cri启动containerd
    --data-root string Root directory of persistent Docker state (default "/var/lib/docker") : 持久Docker状态的根目录(默认为“/var/lib/Docker”)
    -D, --debug Enable debug mode : 启用调试模式
    --default-address-pool pool-options Default address pools for node specific local networks : 特定于节点的本地网络的默认地址池
    --default-cgroupns-mode string Default mode for containers cgroup namespace ("host" | "private") (default "private") : 容器的默认模式cgroup命名空间(“host”|“private”)(默认为“private“)
    --default-gateway ip Container default gateway IPv4 address : 容器默认网关IPv4地址
    --default-gateway-v6 ip Container default gateway IPv6 address : 容器默认网关IPv6地址
    --default-ipc-mode string Default mode for containers ipc ("shareable" | "private") (default "private") : 容器的默认模式ipc(“shareable”|“private”)(默认“private)
    --default-network-opt mapmap Default network options (default map[]) : 默认网络选项(默认地图[])
    --default-runtime string Default OCI runtime for containers (default "runc") : 容器的默认OCI运行时(默认“runc”)
    --default-shm-size bytes Default shm size for containers (default 64MiB) : 容器的默认shm大小(默认64MiB)
    --default-ulimit ulimit Default ulimits for containers (default []) : 容器的默认ulimits(默认[])
    --dns list DNS server to use : 要使用的DNS服务器
    --dns-opt list DNS options to use : 要使用的DNS选项
    --dns-search list DNS search domains to use : 要使用的DNS搜索域
    --exec-opt list Runtime execution options : 运行时执行选项
    --exec-root string Root directory for execution state files (default "/var/run/docker") : 执行状态文件的根目录(默认为“/var/run/docker”)
    --experimental Enable experimental features : 启用实验功能
    --fixed-cidr string IPv4 subnet for fixed IPs : 固定IP的IPv4子网
    --fixed-cidr-v6 string IPv6 subnet for fixed IPs : 固定IP的IPv6子网
    -G, --group string Group for the unix socket (default "docker") : unix套接字的组(默认的“docker”)
    --help Print usage : 打印使用情况
    -H, --host list Daemon socket(s) to connect to : 要连接到的守护程序套接字
    --host-gateway-ip ip IP address that the special 'host-gateway' string in --add-host resolves to. : 添加主机中的特殊“主机网关”字符串解析到的IP地址。
    Defaults to the IP address of the default bridge : 默认为默认网桥的IP地址
    --http-proxy string HTTP proxy URL to use for outgoing traffic : 用于传出流量的HTTP代理URL
    --https-proxy string HTTPS proxy URL to use for outgoing traffic : 用于传出流量的HTTPS代理URL
    --icc Enable inter-container communication (default true) : 启用容器间通信(默认为true)
    --init Run an init in the container to forward signals and reap processes : 在容器中运行init以转发信号和获取进程
    --init-path string Path to the docker-init binary : docker init二进制文件的路径
    --insecure-registry list Enable insecure registry communication : 启用不安全的注册表通信
    --ip ip Default IP when binding container ports (default 0.0.0.0) : 绑定容器端口时的默认IP(默认0.0.0.0)
    --ip-forward Enable net.ipv4.ip_forward (default true) : 启用net.ipv4.ip_forward(默认为true)
    --ip-masq Enable IP masquerading (default true) : 启用IP伪装(默认为true)
    --ip6tables Enable addition of ip6tables rules (experimental) : 启用添加ip6tables规则(实验)
    --iptables Enable addition of iptables rules (default true) : 启用添加iptables规则(默认为true)
    --ipv6 Enable IPv6 networking : 启用IPv6网络
    --label list Set key=value labels to the daemon : 为守护进程设置key=value标签
    --live-restore Enable live restore of docker when containers are still running : 当容器仍在运行时启用docker的实时恢复
    --log-driver string Default driver for container logs (default "json-file") : 容器日志的默认驱动程序(默认的“json文件”)
    -l, --log-level string Set the logging level ("debug"|"info"|"warn"|"error"|"fatal") (default "info") : 设置日志记录级别(“debug”|“info”|“warn”|“error”|“fatal”)(默认为“info”)
    --log-opt map Default log driver options for containers (default map[]) : 容器的默认日志驱动程序选项(默认映射[])
    --max-concurrent-downloads int Set the max concurrent downloads (default 3) : 设置最大并发下载量(默认为3)
    --max-concurrent-uploads int Set the max concurrent uploads (default 5) : 设置最大并发上传(默认值为5)
    --max-download-attempts int Set the max download attempts for each pull (default 5) : 设置每次拉取的最大下载尝试次数(默认为5次)
    --metrics-addr string Set default address and port to serve the metrics api on : 设置默认地址和端口以在上提供度量api
    --mtu int Set the containers network MTU (default 1500) : 设置容器网络MTU(默认1500)
    --network-control-plane-mtu int Network Control plane MTU (default 1500) : 网络控制平面MTU(默认1500)
    --no-new-privileges Set no-new-privileges by default for new containers : 默认情况下不为新容器设置新权限
    --no-proxy string Comma-separated list of hosts or IP addresses for which the proxy is skipped : 跳过代理的主机或IP地址的逗号分隔列表
    --node-generic-resource list Advertise user-defined resource : 播发用户定义的资源
    --oom-score-adjust int Set the oom_score_adj for the daemon : 设置守护程序的oom_score_adj
    -p, --pidfile string Path to use for daemon PID file (default "/var/run/docker.pid") : 用于守护进程PID文件的路径(默认为“/var/run/docker.PID”)
    --raw-logs Full timestamps without ANSI coloring : 无ANSI着色的完整时间戳
    --registry-mirror list Preferred registry mirror : 首选注册表镜像
    --rootless Enable rootless mode; typically used with RootlessKit : 启用无根模式;通常与RootlessKit一起使用
    --seccomp-profile string Path to seccomp profile. Use "unconfined" to disable the default seccomp profile (default "builtin") : seccomp配置文件的路径。使用“unconfined”禁用默认的seccomp配置文件(默认的“内置”)
    --selinux-enabled Enable selinux support : 启用selinux支持
    --shutdown-timeout int Set the default shutdown timeout (default 15) : 设置默认关机超时(默认15)
    -s, --storage-driver string Storage driver to use : 要使用的存储驱动程序
    --storage-opt list Storage driver options : 存储驱动程序选项
    --swarm-default-advertise-addr string Set default address or interface for swarm advertised address : 为群通告地址设置默认地址或接口
    --tls Use TLS; implied by --tlsverify : 使用TLS;由--tlsverify暗示
    --tlscacert string Trust certs signed only by this CA (default "~/.docker/ca.pem") : 仅由该CA签名的信任证书(默认为“~/.docker/CA.pem”)
    --tlscert string Path to TLS certificate file (default "~/.docker/cert.pem") : TLS证书文件的路径(默认为“~/.docker/cert.pem”)
    --tlskey string Path to TLS key file (default "~/.docker/key.pem") : TLS密钥文件的路径(默认为“~/.docker/key.pem”)
    --tlsverify Use TLS and verify the remote : 使用TLS并验证远程
    --userland-proxy Use userland proxy for loopback traffic (default true) : 对环回流量使用userland代理(默认为true)
    --userland-proxy-path string Path to the userland proxy binary : userland代理二进制文件的路径
    --userns-remap string User/Group setting for user namespaces : 用户命名空间的用户/组设置
    --validate Validate daemon configuration and exit : 验证守护程序配置并退出
    -v, --version Print version information and quit : 打印版本信息并退出

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
29
30
31
32
docker version # 查看docker的版本号,包括客户端、服务端、依赖的Go等
docker info # 查看系统(docker)层面信息,包括管理的images, containers数等
docker search <image> # 在docker index中搜索image
docker pull <image> # 从docker registry server 中下拉image

docker images: # 列出images
docker images -a # 列出所有的images(包含历史)
docker rmi <image ID>: # 删除一个或多个image

docker run -i -t sauloal/ubuntu14.04
docker run -i -t sauloal/ubuntu14.04 /bin/bash # 创建一个容器,让其中运行 bash 应用,退出后容器关闭
docker run -itd --name centos_aways --restart=always centos #创建一个名称centos_aways的容器,自动重启

--restart参数:always始终重启;on-failure退出状态非0时重启;默认为,no不重启

docker ps ;列出当前所有正在运行的container
docker ps -l :列出最近一次启动的container
docker ps -a :列出所有的container(包含历史,即运行过的container)
docker ps -q :列出最近一次运行的container ID

docker start/stop/restart <container> #:开启/停止/重启container
docker start [container_id] #:再次运行某个container (包括历史container)

docker stop <容器的CONTAINER ID>

docker exec -it [container_id] /bin/bash
docker run -i -t -p <host_port:contain_port> #:映射 HOST 端口到容器,方便外部访问容器内服务,host_port 可以省略,省略表示把 container_port 映射到一个动态端口。

docker rm <container...> #:删除一个或多个container
docker rm `docker ps -a -q` #:删除所有的container
docker ps -a -q | xargs docker rm #:同上, 删除所有的container

安装docker-compose

1
sudo curl -L https://github.com/docker/compose/releases/download/v2.23.3/docker-compose-`uname -s`-`uname -m` -o /usr/local/bin/docker-compose

修改国内镜像地址

安装mysql

1
2
3
4
5
6
7
8
9
docker run   --name test-mysql  -p 13306:3306  -e MYSQL_ROOT_PASSWORD=123456  -d mysql:5.7
docker cp test-mysql:/etc/mysql /data/app/mysql5.7/cnf
docker cp test-mysql:/etc/mysql /data/app/mysql5.7/cnf
docker cp test-mysql:/var/lib/mysql /data/app/mysql5.7/data
docker cp test-mysql:/var/log /data/app/mysql5.7/log
docker cp test-mysql:/var/lib/mysql-files /data/app/mysql5.7/mysql-files

docker rm -f test-mysql
docker run --restart=always --name test-mysql -v /data/app/mysql5.7/cnf:/etc/mysql -v /data/app/mysql5.7/data:/var/lib/mysql -v /data/app/mysql5.7/log:/var/log -v /data/app/mysql5.7/mysql-files:/var/lib/mysql-files -p 13306:3306 -e MYSQL_ROOT_PASSWORD=123456 -d mysql:5.7

安装 zk / kafka /redis

docker-compose up -d

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
version: '3.8'
services:
zookeeper:
image: wurstmeister/zookeeper
ports:
- "2181:2181"
mem_limit: 256m
kafka:
image: wurstmeister/kafka
depends_on: [ zookeeper ]
ports:
- "9092:9092"
environment:
#KAFKA_ADVERTISED_HOST_NAME: kafka
KAFKA_ADVERTISED_HOST_NAME: 192.168.16.130
KAFKA_CREATE_TOPICS: "test:1:1"
KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
mem_limit: 1024m
redis-master:
image: redis:3.2.3-alpine
container_name: redis_n
ports:
- 16379:6379
volumes:
- /etc/timezone:/etc/timezone:ro
- /etc/localtime:/etc/localtime:ro
- /data/app/redis/redis.conf:/usr/local/etc/redis/redis.conf:rw
- /data/app/redis/data:/data:rw
mem_limit: 512m