目录
1. 拉取nginx镜像
docker pull nginx
2. 创建并编辑nginx.conf文件,本例中放在/usr/local/nginx下。
events {
# 指定最大并发连接数
worker_connections 1024;
}
http {
include mime.types;
# 指定默认的MIME类型
default_type application/octet-stream;
# 开启高效文件传输模式
sendfile on;
# 定义keep-alive连接的超时时间(120s)
keepalive_timeout 120;
# 客户端请求的最大请求体大小为 50 MB
client_max_body_size 50m;
# 客户端请求体缓冲区的大小为 10 MB
client_body_buffer_size 10m;
# 定义读取客户端请求头的超时时间为 1 分钟
client_header_timeout 1m;
# 定义读取客户端请求体的超时时间为 1 分钟
client_body_timeout 1m;
# 开启 gzip 压缩
gzip on;
# 启用压缩的最小文件大小为 1 KB
gzip_min_length 1k;
# 压缩时的缓冲区大小
gzip_buffers 4 16k;
# 设置压缩级别为4,即中等压缩比
gzip_comp_level 4;
# 定义需要进行压缩的 MIME 类型。
gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
# 在响应头中添加 "Vary: Accept-Encoding",用于缓存服务器根据 Accept-Encoding 头字段进行区分缓存
gzip_vary on;
server {
listen 80 default_server; # 80端口
server_name _;
location / {
root /usr/local/abc/blog; # 前台前端
index index.html index.htm;
try_files $uri $uri/ /index.html ;
proxy_pass http://服务器ip:8080/; # 转发到后端
}
}
server {
listen 81 default_server; # 81端口
server_name _;
location / {
root /usr/local/abc/admin; # 后台前端
index index.html index.htm;
try_files $uri $uri/ index.html ;
proxy_pass http://服务器ip:8080/; # 转发到后端
}
}
}
注意不要写错前端资源路径。
3. Docker运行nginx
docker run --name nginx --restart=always -p 80:80 -p 81:81 -d -v /usr/local/nginx/nginx.conf:/etc/nginx/nginx.conf -v /usr/local/abc:/usr/local/abc nginx
在使用Docker运行时,注意指定需要映射的端口。使用多个 '-p' 参数可注定多个端口映射。
4. 错误处理
使用以下命令查看nginx日志
docker logs -f nginx
①如果访问http://服务器ip/ 后,日志没有出现响应,请检查相应的端口是否已开放。
②如果日志出现以下错误:
[error] 28#28: *7 rewrite or internal redirection cycle while internally redirecting to "/index.html", .....................
检查前端资源路径是否正确配置。