docker - NGINX和Docker的反向代理

标签 docker nginx reverse-proxy

我有一个使用我制作的docker镜像在http://localhost:8000上运行的应用程序。

现在,我想使用NGINX作为侦听端口80的反向代理,以重定向到localhost:8000。

这是我的nginx.conf文件

#user  nobody;
worker_processes  1;
events {
    worker_connections  1024;
}
http {
    server {
        listen 80;
        location / {
            proxy_pass http://localhost:8000;
        }
    }
}

这是我的Dockerfile:
FROM nginx

RUN rm /etc/nginx/conf.d/default.conf

COPY index.html /usr/share/nginx/html
COPY nginx.conf /etc/nginx

CMD nginx

要构建图像,我使用命令
docker build --no-cache -t mynginx .

要运行它,我使用
docker run -p 80:80 -d mynginx 

现在,如果我使用curl localhost:8000在本地计算机上进行测试,那么一切正常,但是如果我尝试使用curl localhost,则会收到错误的网关错误。

此外,我尝试提供静态内容并且可以使用,但是使用反向代理设置则无法使用。

最佳答案

您收到错误的网关的原因是,在您的nginx容器中,localhost解析为容器本身而不是主机系统。

如果要从反向代理容器访问应用程序容器,则需要将两个容器都放入网络。

docker network create my-network
docker network connect --alias application my-network <application container id/name>
docker network connect --alias reverse-proxy my-network <reverse proxy container id/name>
--network可以是任意名称,而--alias应该是您要解析到容器的主机名。
实际上,如果您已经为容器分配了(主机)名称(docker run --name ...),则无需提供别名。

然后,您可以将proxy_pass指令更改为应用程序容器的(别名)名称:
proxy_pass http://application:8000;

另请参阅文档:Container networking

关于docker - NGINX和Docker的反向代理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54349700/

相关文章:

docker-volume - 无法将卷标志与 Windows 容器一起使用

java - 无法自动检测kubelet URL : datadog_checks. base.errors.CheckException

nginx 连接到上游 https 时没有实时上游

docker - 我需要多少个Docker容器,如何在它们之间分隔代码?

jquery - 为子域 B 设置子域 A 的 cookie

nginx - 预渲染无法在 Nginx 上使用 https

ubuntu - Nginx 作为虚拟主机和反向代理

docker - nginx 反向代理后面的 Jenkins 不会在所有情况下重定向

iis-7 - IIS ARR (edge) cache (reverse proxy) - 上游连接超时问题

ssl - 使用 Docker 向 Lita 机器人添加 SSL 证书