Docker容器下运行Nginx并实现反向代理

769 阅读1分钟

运行 Nginx 容器

  • 获取 nginx 镜像

    docker pull nginx

  • 运行 nginx 镜像

    docker run --name=nginx -d -p 80:80 nginx

    • --name:设置容器的名称
    • -d:表示在后台运行容器
    • -p:指定端口映射。80是宿主机的端口,80是Nginx容器内部的端口
    • nginx:表示根据nginx镜像运行容器
  • 在浏览器上输入您服务器的ip访问,出现 welcome to nginx 说明你的 nginx 容器已成功运行

运行你要实现反向代理的 docker 服务

  • 运行您的服务xxx

    docker run --name=xxx -d -p 3000:3000 xxx

  • 在浏览器上输入您服务器的ip:3000访问

设置 nginx 反向代理

  • 在nginx容器中运行

    docker exec -it nginx /bin/bash

    • -it:表示分配一个伪终端
    • nginx:表示容器的名称,这里也可以使用容器ID
    • /bin/bash:表示对容器执行bash操作
  • nginx 默认安装在 /etc/nginx 目录

  • 进入到 nginx 目录,查看默认配置

    vim /etc/nginx/nginx.conf

    image.png

    表示使用的是 conf.d 目录下面的 *.conf 文件进行配置

  • 找到您服务xxx的IP地址

    docker inspect xxx

    image.png

  • 新建一个xxx.conf

    vim /etc/nginx/conf.d/xxx.conf

    image.png

  • 退出容器服务 exit

  • 重启 nginx

    docker restart nginx

  • 在浏览器访问 a.abc.com 成功代理到3000端口

  • 大功告成,谢谢~