- 制作nginx镜像
到 Docker Hub 搜索nginx
,选择自己需要的镜像
Dockerfile 中引入即可:
FROM nginx
直接打包启动镜像,默认为80端口
- 镜像中文件路径说明:
/usr/share/nginx/html web静态资源存放在该路径
/etc/nginx/nginx.conf nginx主配置文件
/etc/nginx/conf.d 子配置文件夹至少包含一个default.conf配置
nginx启动时先加载一个主配置文件nginx.conf,在nginx.conf里再加载conf.d目录下的子配置文件
一般我们的配置信息写在default.conf
文件中
- 启动镜像时挂载配置文件
docker run \
--name myNginx \
-d -p 80:80 \
-v /root/wang/html:/usr/share/nginx/html \
-v /root/wang/nginx.conf:/etc/nginx/nginx.conf:ro \
-v /root/wang/conf.d:/etc/nginx/conf.d \
nginx
这样就可以把自己服务器上的资源挂载到镜像内,修改配置时只用修改本地的配置就好了-v /root/wang/html:/usr/share/nginx/html
挂载web资源到容器内-v /root/wang/nginx.conf:/etc/nginx/nginx.conf:ro
挂载主配置-v /root/wang/conf.d:/etc/nginx/conf.d
挂载conf.d下的所有配置
- 配置文件详情
nginx.conf
user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log warn;
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;
# 包含conf.d 配置路径
include /etc/nginx/conf.d/*.conf;
}
default.conf配置内容
server {
location /api {
rewrite /api/(.*) /$1 break;
proxy_pass http://192.168.10.140:32274/;
proxy_set_header X-Real-IP $remote_addr;
}
}
- nginx 配置说明
rewrite:
- 如果正则表达式(regex)匹配到了请求的URI(request URI),这个URI会被后面的replacement替换
- rewrite的定向会根据他们在配置文件中出现的顺序依次执行
- 通过使用flag可以终止定向后进一步的处理
- 如果replacement以“http://”, “https://”, or “$scheme”开头,处理将会终止,请求结果会以重定向的形式返回给客户端(client)
- 如果replacement字符串里有新的request参数,那么之前的参数会附加到其后面,如果要避免这种情况,那就在replacement字符串后面加上“?”,eg:
rewrite ^/users/(.*)$ /show?user=$1? last;=
- 如果正则表达式(regex)里包含“}” or “;”字符,需要用单引号或者双引号把正则表达式引起来
proxy_pass:
设置被代理server的协议和地址,URI可选(可以有,也可以没有)
- 如果proxy_pass的URL定向里包括URI,那么请求中匹配到location中URI的部分会被proxy_pass后面URL中的URI替换,eg:
location /name/ {
proxy_pass http://example.com/remote/;
}
请求http://127.0.0.1/name/test.html 会被代理到http://example.com/remote/test.html
- 如果proxy_pass的URL定向里不包括URI,那么请求中的URI会保持原样传送给后端server,eg:
location /name {
proxy_pass http://example.com;
}
请求http://127.0.0.1/name/test.html 会被代理到http://example.com/name/test.html
- 请求中匹配到location中的URI,在proxy_pass中去掉对应的URI
location /name {
rewrite /name/(.*) /$1 break;
proxy_pass http://example.com/;
}
请求http://127.0.0.1/name/test.html 会被代理到http://example.com/test.html
proxy_set_header: 设置header
有时候需要请求被nginx代理后,能够带上用户的真实IP,可以在nginx中获取到用户真实IP后,添加到Header中
location /api {
rewrite /api/(.*) /$1 break;
proxy_pass http://192.168.10.140:32274/;
proxy_set_header X-Real-IP $remote_addr;
}
$remote_addr 可以获取用户的真实请求IP