tutorial/Writerside/topics/Docker常见问题.md
2025-04-20 23:11:40 +08:00

100 lines
2.8 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Docker常见问题
## 1. Docker镜像拉取失败
> 可以尝试更换镜像源
>
> 首先进入打开daemon配置文件
>
> ```sh
> #执行
> nano /etc/docker/daemon.json
> # 或者
> vim /etc/docker/daemon.json
> ```
>
> 一般是空的文件,我们可以把网上找到的镜像源粘贴到上面,格式形如
>
> ```json
> {
> "dns": ["8.8.8.8", "8.8.4.4"],
> "registry-mirrors": [
> "https://docker.mirrors.sjtug.sjtu.edu.cn",
> "https://cr.laoyou.ip-ddns.com",
> "https://docker.1panel.live",
> "https://image.cloudlayer.icu",
> "https://hub.fast360.xyz",
> "https://docker-0.unsee.tech",
> "https://docker.1panelproxy.com",
> "https://docker.tbedu.top",
> "https://dockerpull.cn",
> "https://docker.m.daocloud.io",
> "https://hub.rat.dev",
> "https://docker.kejilion.pro",
> "https://docker.hlmirror.com",
> "https://docker.imgdb.de",
> "https://docker.melikeme.cn",
> "https://ccr.ccs.tencentyun.com"
> ]
> }
> ```
>
> 然后重启Docker服务即可
>
> ```sh
> sudo systemctl restart docker
> ```
## 2. Docker容器自启动
> 这里拿pgsql举例
### **方法 1使用 `docker run` 时设置自启动**
在运行容器时,使用 `--restart` 参数指定重启策略
```
docker run --name my-postgres \
-e POSTGRES_PASSWORD=mysecretpassword \
-p 5432:5432 \
-v /var/lib/postgresql/data:/var/lib/postgresql/data \
--restart unless-stopped \ # 关键参数:设置自启动策略
-d postgres
```
### **`--restart` 可选策略**
| 策略 | 说明 |
| :------------------------- | :----------------------------------------------------------- |
| `no` | **默认**,容器不会自动重启 |
| `always` | **总是重启**(即使手动停止 `docker stop`Docker 服务重启后也会自动启动) |
| `unless-stopped` | **除非手动停止**`docker stop` 后不会自启,其他情况如系统重启会自动恢复) |
| `on-failure[:max-retries]` | **失败时重启**(可设置最大重试次数,如 `on-failure:5` |
------
### **方法 2修改已运行的容器**
如果容器已经创建,可以用 `docker update` 修改其重启策略:
```
docker update --restart unless-stopped my-postgres
```
------
### **方法 3在 `docker-compose.yml` 中配置**
如果使用 Docker Compose`services` 下添加 `restart` 字段:
```
services:
postgres:
image: postgres
container_name: my-postgres
restart: unless-stopped # 可选 always / on-failure / no
environment:
POSTGRES_PASSWORD: mysecretpassword
volumes:
- /var/lib/postgresql/data:/var/lib/postgresql/data
ports:
- "5432:5432"
```