在 Ubuntu 上让 Docker 自启 和 容器自启,通常分两种情况:
sudo systemctl enable docker
sudo systemctl start docker
systemctl status docker
如果看到
enabled,说明已设好自启
docker run -d --restart=always --name mycontainer nginx
常用 --restart 参数:
no:不自启(默认)on-failure:非正常退出才重启always:总是自启(包括开机)unless-stopped:手动 stop 后不开机自启docker update --restart=always mycontainer
在 docker-compose.yml 中:
version: "3"
services:
web:
image: nginx
restart: always
然后:
docker compose up -d
sudo reboot
重启后:
docker ps
如果你是用 WSL / 服务器 / 云主机,可以告诉我环境,我可以给你更精确的方案。