可以通过以下两种方法让 Docker 一直保持运行:
- 使用 Docker Compose
在使用 Docker Compose 的时候,可以使用 docker-compose up -d
命令来启动容器,并使用 -d
参数将其置于后台运行。这样就可以保证容器始终处于运行状态,即使退出了终端也不会停止。
- 使用 Systemd
对于 Linux 系统,还可以使用 systemd 来管理 Docker 容器的运行。具体步骤如下:
- 创建一个新的文件
/etc/systemd/system/docker.service
:
[Unit]
Description=Docker Application Container Engine
Documentation=https://docs.docker.com/
After=network-online.target docker.socket firewalld.service
Wants=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/docker daemon -H fd:// --containerd=/run/containerd/containerd.sock
ExecReload=/bin/kill -s HUP $MAINPID
LimitNOFILE=1048576
LimitNPROC=infinity
LimitCORE=infinity
TimeoutStartSec=0
Restart=always
[Install]
WantedBy=multi-user.target
2) 启用该服务并重新加载 systemctl 配置:
sudo systemctl enable docker.service sudo systemctl daemon-reload
3) 启动 Docker 服务并检查状态:
sudo systemctl start docker.service sudo systemctl status docker.service “`
此时,Docker 容器应该已经在系统中启动并运行,即使退出了终端也不会停止。