docker之安装nginx

一.拉取镜像

docker pull nginx

二.创建挂载映射目录

1.创建nginx配置目录
mkdir -p /opt/docker-nginx/conf
2.创建nginx的日志文件目录
mkdir -p /opt/docker-nginx/logs
3.创建nginx的html
mkdir -p /opt/docker-nginx/html

三.配置启动参数启动容器

1.配置实例并启动
docker  run -p 80:80  --name nginx -v /opt/docker-nginx/html:/usr/share/nginx/html -v /docker-nginx/nginx/logs:/var/log/nginx   -d nginx
2.复制docker内nginx配置文件目录到本地配置文件目录,以便修改

本地nginx配置文件目录是 /opt/docker-nginx/conf/

docker内部nginx的配置文件目录是 /etc/nginx

复制docker内配置文件目录到本地路径

docker container cp nginx:/etc/nginx/ /opt/docker-nginx/conf/
3.删除容器,重新配置实例运行

(1)停止nginx容器

docker stop nginx

(2)删除nginx容器

nginx rm nginx

(3)配置实例运行

docker  run -p 80:80 --restart=always --name nginx -v /opt/docker-nginx/html:/usr/share/nginx/html -v /opt/docker-nginx/logs:/var/log/nginx -v /opt/docker-nginx/conf/nginx/conf.d:/etc/nginx/conf.d  -d nginx

参数说明:

  • -p 80:80 端口映射到本地端口
  • –name nginx 容器别名
  • -v 配置目录挂载映射
  • -d nginx 后他启动

四.反向代理

目的:将部署的springboot项目mall通过nginx进行反向代理或者负载均衡

1.重新配置nginx容器参数启动
docker  run -p 80:80 --restart=always --name nginx --link mall:mall -v  /opt/docker-nginx/html:/usr/share/nginx/html -v /opt/docker-nginx/logs:/var/log/nginx -v /opt/docker-nginx/conf/nginx/conf.d:/etc/nginx/conf.d  -d nginx

在前面的启动参数加了

  • –link mall:mall 将容器外的mall容器通过别名mall映射到该容器中
2.增加mall.conf配置文件
[root@localhost conf.d]# vim mall.conf
server {
    listen  80;
    server_name localhost;
    access_log /var/log/nginx/mall.access.log main;
    error_log /var/log/nginx/mall.error.log error;
    location / {
        proxy_set_header  Host  $http_host;
        proxy_set_header  X-Real-IP  $remote_addr;
        proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass  http://mall;
    }
}
 upstream mall{
     server mall:8080;
    }
3.重新启动nginx

重新启动

docker restart nginx

访问宿主机 192.168.102.129

访问则跳转到 mall:8080

参考文章

https://blog.csdn.net/weixin_39797865/article/details/79280625

五.问题解决

1.端口反向代理配置,后启动访问,报错
 *2 connect() failed (113: No route to host) while connecting to upstream, client: 192.168.102.1, server: 192.168.102.129, request: "GET / HTTP/1.1", upstream: "http://192.168.102.129:8080/", host: "192.168.102.129"

解决:

2.访问不了主页

问题如下:

directory index of "/usr/share/nginx/html/" is forbidden, client: 192.168.102.1, server: localhost, request: "GET / HTTP/1.1", host: "192.168.102.129"

本例中因为宿主机里面/opt/docker-nginx/html下面的index文件,修改为index.html 重启即可

参考文章

https://blog.csdn.net/onlysunnyboy/article/details/75270533

©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页