docker安装nginx设置转发规则
1、下载最新nginx镜像
docker pull nginx
Using default tag: latest
latest: Pulling from library/nginx
Digest: sha256:8f335768880da6baf72b70c701002b45f4932acae8d574dedfddaf967fc3ac90
Status: Image is up to date for nginx:latest
docker.io/library/nginx:latest
镜像下载成功后,可使用
nginx -v
检查nginx
的版本,当前下载最新的镜像对应的nginx
版本为1.21.1
docker run --rm nginx bash -c "nginx -v"
nginx version: nginx/1.21.1
2、初始运行nginx并将配置文件拷贝到宿主机
- 启动一个临时nginx,将配置文件拷贝到宿主机
docker run -it --rm --name nginx nginx
- 新打开一个命令窗口,将nginx配置文件拷贝到宿主机
docker cp nginx:/etc/nginx/. /data/nginx/conf
同时可将日志拷贝到宿主机(可省略)
docker cp nginx:/var/log/nginx/access.log /data/nginx/log/
docker cp nginx:/var/log/nginx/error.log /data/nginx/log/
完成文件拷贝后,将此临时nginx关闭
3、挂载宿主机nginx配置文件目录及日志目录启动nginx
docker run -d -p 8080:80 --restart=always --name nginx -v /data/nginx/conf/:/etc/nginx/ -v /data/nginx/log/:/var/log/nginx/ -e TZ=Asia/Shanghai nginx
注意防火墙配置8080端口规则,接下来就可以自行修改nginx的配置文件了(/data/nginx/conf/conf.d)
- 设置转发到本地8081端口
server {
listen 80;
listen [::]:80;
server_name www.mixfate.com;
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $http_host;
proxy_pass http://127.0.0.1:8081;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
4、如nginx及jekyll均使用docker启用,可使用docker-compose配置,配置文件如下
version: "3.9"
services:
jekyll:
image: jekyll/jekyll:4.1.0-fix-v2
container_name: dc-jekyll
ports:
- "4000:4000"
volumes:
- "/project/mixfate/:/srv/jekyll/"
environment:
TZ: Asia/Shanghai
command: jekyll server -w
nginx:
image: nginx:latest
container_name: dc-nginx
ports:
- "80:80"
- "443:443"
volumes:
- "/data/nginx/conf/:/etc/nginx/"
- "/data/nginx/log/:/var/log/nginx/"
environment:
TZ: Asia/Shanghai