一、安装Nginx环境
- 拉取 nginx 镜像
docker pull nginx:latest
- 运行一个临时容器,用于拷贝内部的config文件
docker run --rm -d --name nginx:latest nginx-temp
- 在宿主机上生成nginx配置、静态资源目录以及日志相关的目录映射
mkdir -p ./nginx/{conf,html,logs}
- 将容器内的
nginx.conf和default.conf到 宿主机的/conf目录中
docker cp nginx-temp:/etc/nginx/nginx.conf ./
docker cp nginx-temp:/etc/nginx/conf.d/default.conf ./conf/
- 删除临时容器
docker stop nginx-temp
# 如果没有加 --rm 参数,则需要手动删除容器
docker rm nginx-temp
- 运行新的 nginx 容器
docker run -d --name nginx -p 80:80 -v /root/nginx/conf/nginx.conf:/etc/nginx/nginx.conf -v /root/nginx/conf:/etc/nginx/conf.d -v /root/nginx/html:/usr/share/nginx/html -v
/root/nginx/logs:/var/log/nginx --privileged=true nginx:latest
# -v: 表示将主机目录与容器目录之间的共享
# --privileged=true 容器内部对挂载的目录拥有读写等特权
- 在
/root/nginx/html目录中创建index.html文件,然后访问主机IP即可访问到页面。
二、nginx 的基本配置
- 查看 nginx.conf
cat nginx/nginx.conf
# 初始配置
main # 全局配置
events { # nginx 工作模式配置
}
http { # http 设置
....
server { # 服务器主机配置
....
location { # 路由配置
....
}
location path {
....
}
location otherpath {
....
}
}
server {
....
location {
....
}
}
upstream name { # 负载均衡配置
....
}
}
- 配置静态资源的访问
server{
listen 80;
server_name localhost; # 公网IP 或 域名
index index.html index.htm;
location / {
root /usr/share/nginx/html
index index.html index.htm
}
}
- 域名转发
server{
listen 80;
server_name test.site.com;
index index.html index.htm;
location / {
proxy_pass http://www.baidu.com;
proxy_set_header Host $proxy_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
- 端口转发
server{
listen 80;
server_name test.site.com;
index index.html index.htm;
location /express/ {
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $proxy_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
proxy_pass 后面的地址是否加 / 的区别
- 加
/代表根绝对路径:test.site.com/express/ind… 转发到 http://127.0.0.1:8080/index.html - 不加
/:代表相对路径:test.site.com/express/ind… 转发到 http://127.0.0.1:8080/express/index.html
- 负载均衡配置
# 在http里:
upstream backend {
server 127.0.0.1:81;
server 127.0.0.1:82;
}
# 在server里:
location / {
proxy_pass http://backend;
}