安装nginx
1. 安装最新镜像
podman pull nginx:latest
2. 启动一个临时容器用来提取文件
mkdir -p /home/wt/nginx/{nginx_html,nginx_conf,nginx_logs}
4. 把默认配置文件拷贝到你宿主机对应的目录
bash
# 拷贝 nginx.conf
podman cp nginx-temp:/etc/nginx/nginx.conf /home/wt/nginx/nginx_conf/
# 拷贝 conf.d 目录(里面有默认的 default.conf)
podman cp nginx-temp:/etc/nginx/conf.d /home/wt/nginx/nginx_conf/
# 拷贝 mime.types 等其他必要文件
podman cp nginx-temp:/etc/nginx/mime.types /home/wt/nginx/nginx_conf/
5. 删掉临时容器
bash
podman rm -f nginx-temp
6. 启动 Nginx 容器
podman run -d \
--name nginx-spzx \
-p 3030:80 \
-v /home/wt/nginx/nginx_html:/usr/share/nginx/html \
-v /home/wt/nginx/nginx_conf:/etc/nginx/ \
-v /home/wt/nginx/nginx_logs:/var/log/nginx \
docker.io/library/nginx:latest
💡 验证结果
-
执行
podman ps,看看nginx-spzx是否在运行列表里。 -
浏览器访问
http://localhost:3030,应该能看到 Nginx 的欢迎页面。 -
此时去查看宿主机的
/home/wt/nginx/nginx_conf/目录,你会发现里面已经有文件了,以后你想改配置,直接改这里的nginx.conf或conf.d/default.conf即可。 -
修改配置后,记得重启容器生效:
podman restart nginx-spzx
⚠️ 补充一个小知识(重要):
你用 -v /home/wt/nginx/nginx_html:/usr/share/nginx/html 挂载了 HTML 目录,但宿主机的 /home/wt/nginx/nginx_html 大概率也是空的。
如果你连进去,发现页面显示 403 Forbidden,那是因为目录里没有 index.html。
如果遇到 403,你只需要往宿主机的 /home/wt/nginx/nginx_html 目录里放一个 index.html 文件就行了。(把自己的静态资源文件就放这个目录里)
设置开机自启
为这个 Nginx 容器设置开机自启,同样推荐使用 Quadlet 方式。从你使用的挂载路径 /home/wt/... 来看,容器应该是以普通用户 wt 运行的(无根模式),下面按无根模式给出步骤。如果你的容器实际是以 root 运行的,文末会说明差异。
步骤 1:停止并删除手动创建的容器
Quadlet 服务会自己创建并管理同名容器。为避免名称冲突和端口 3030 被占用,先清理掉你手动 run 出来的那个容器:
podman stop nginx-spzx
podman rm nginx-spzx
步骤 2:编写 Quadlet 文件
mkdir -p ~/.config/containers/systemd/
创建 ~/.config/containers/systemd/nginx-spzx.container,内容如下:
[Unit]
Description=Nginx Container (spzx)
[Container]
Image=docker.io/library/nginx:latest
ContainerName=nginx-spzx
PublishPort=3030:80
Volume=/home/wt/nginx/nginx_html:/usr/share/nginx/html:Z
Volume=/home/wt/nginx/nginx_conf:/etc/nginx/:Z
Volume=/home/wt/nginx/nginx_logs:/var/log/nginx:Z
[Service]
Restart=always
RestartSec=5
[Install]
WantedBy=default.target
几点说明:
-
Volume路径必须是绝对路径:/home/wt/...正好满足,无需改动。systemd 无法解析~。 -
关于
:Z:你的原命令没加 SELinux 标签。如果系统启用了 SELinux(Fedora / RHEL / CentOS 等),Nginx 读取挂载目录会被拒绝,需要加:Z。如果系统未启用 SELinux(如 Ubuntu / Debian 默认),加不加都行。上面已统一加上,更稳妥。 -
nginx_conf挂载了整个/etc/nginx/:请确认宿主目录/home/wt/nginx/nginx_conf里已有完整的 nginx 配置(至少nginx.conf、conf.d/、mime.types等)。如果该目录是空的,容器启动后 Nginx 会因找不到配置而退出,表现为服务反复重启。这是这个挂载方式最常见的坑。 -
[Install] WantedBy=default.target就是"开机自启"的声明,systemd 会在default.target达成时拉起该服务。
步骤 3:开启 linger(无根模式必做)
无根用户服务默认只在你登录后才启动。要让容器在开机后、登录前就运行,必须为 wt 用户开启 lingering:
sudo loginctl enable-linger wt
(如果当前就是 wt 用户,可以简写为 sudo loginctl enable-linger "$USER"。如果你之前为 silo 已经执行过,这一步可跳过。)
步骤 4:加载并启动服务
systemctl --user daemon-reload
systemctl --user start nginx-spzx.service
注意:Quadlet 生成的服务不需要手动 enable,[Install] 段已经声明了自启。
步骤 5:验证
# 查看服务状态
systemctl --user status nginx-spzx.service
# 确认容器在跑
podman ps --filter name=nginx-spzx
# 测试访问
curl -I http://localhost:3030
如果服务状态是 active (running) 且 curl 返回 200 OK,就说明配置成功。之后系统重启,容器会自动拉起。
浙公网安备 33010602011771号