docker-compose 部署 nginx
获取配置文件
nginx 有默认的配置文件,可以从 docker 镜像中获取到
# 运行一个 nginx docker 容器$ docker run --name tmp-nginx-container -d nginx# 从容器中复制出 nginx 的默认配置文件到本地$ docker cp tmp-nginx-container:/etc/nginx/nginx.conf ./nginx.conf# 删除刚刚运行的 nginx docker 容器$ docker rm -f tmp-nginx-container
下面是默认的配置文件
user nginx;worker_processes auto;error_log /var/log/nginx/error.log notice;pid /var/run/nginx.pid;events {worker_connections 1024;}http {include /etc/nginx/mime.types;default_type application/octet-stream;log_format main '$remote_addr - $remote_user [$time_local] "$request" ''$status $body_bytes_sent "$http_referer" ''"$http_user_agent" "$http_x_forwarded_for"';access_log /var/log/nginx/access.log main;sendfile on;#tcp_nopush on;keepalive_timeout 65;#gzip on;include /etc/nginx/conf.d/*.conf;}
其中有一句代码 include /etc/nginx/conf.d/*.conf; 也就是说,我们只要映射到 /etc/nginx/conf.d/*.conf 中就可以自动读取到我们的配置文件,所以直接映射到这个目录下,而不是覆盖原来的默认配置文件,并且可以直接写 server,如下面这个
server {listen 80;listen [::]:80;server_name localhost;# 默认的静态文件路径在 /usr/share/nginx/html 下# 而在 docker 中默认的静态文件路径在 /etc/nginx/html/, 如果写相对路径就会访问这个目录下的location / {root /usr/share/nginx/html;index index.html index.htm;}}
docker-compose.yml
services:nginx:image: nginxcontainer_name: nginxhostname: nginxvolumes:- ./nginx/nginx.conf:/etc/nginx/conf.d/default.confports:- 80:80- 443:443
配置文件,可以使用上面指向 nginx 默认的 html 页面
在 win 上当成 win 本机的 nginx 使用技巧
访问静态文件
由于容器中与宿主机的目录不能互通,只能通过 volumes 映射的方式,所以需要访问宿主机目录时,可以通过卷映射来完成访问;
转发到宿主机服务
location ^~ /api/ {rewrite /api/(.*) /$1 break;proxy_pass http://192.168.1.115:11120;client_max_body_size 500M;}
直接写宿主机的内网 IP 即可完成平时开发时的代理转发功能
