从docker调用docker的主机

时间:2018-01-27 22:29:44

标签: docker nginx

我有一个nginx服务器,其中包含一个在docker中提供的静态html文件。

Dockerfile如下所示:

FROM ubuntu:latest

USER root

RUN apt-get update
RUN apt-get install -y nginx nodejs

# Remove the default Nginx configuration file
RUN rm -v /etc/nginx/nginx.conf

# Copy a configuration file from the current directory
ADD nginx.conf /etc/nginx/

ADD Front-Dev/v2/desktop /usr/share/nginx/html/
ADD Front-Dev/v2/desktop /var/www/html/

# Append "daemon off;" to the beginning of the configuration
RUN echo "daemon off;" >> /etc/nginx/nginx.conf

# Set the default command to execute
# when creating a new container
CMD service nginx start

Docker容器由以下命令执行:sudo docker run -p 9002:9000 pitstop-nginx

在Docker的主机上并行执行带有API的服务器。此服务器在没有Docker的情况下工作,并使用端口9002。

在位于Docker JS中的静态页面中,试图调用服务器API /api/auth/login并且由于请求是在docker中进行的,我获得了502错误。

我该如何解决?你能解释一下我应该在Docker中修改什么来让Docker的请求转到Docker主机吗?

1 个答案:

答案 0 :(得分:0)

  1. 您无法同时运行docker host API server&主机端口9002上的容器。将泊坞窗运行更改为 -

    sudo docker run -p 9003:9000 pitstop-nginx

  2. 使用ipconfigifconfig获取主机私有IP。

  3. 将主机名添加到Docker容器可以理解的私有IP(10.100.101.108 - 我的主机专用IP) -

    sudo docker run --add-host="my-host-machine:10.100.101.108" -p 9003:9000 pitstop-nginx

  4. (如果Docker主机IP可能会发生变化,请使用变量)

    1. 您的主机现在可以使用主机名访问 -

      root@721508a294ad:/# ping my-host-machine 
      PING my-host-machine (10.100.101.108) 56(84) bytes of data.
      64 bytes from my-host-machine (10.100.101.108): icmp_seq=1 ttl=37 time=0.865 ms
      
    2. 在Nginx中使用proxy pass将所有API请求重定向到您的主机 -

      location /api/ {
           proxy_pass http://my-host-machine:9002/;
      }
      
    3. PS - 这是对此问题的快速解决方法。但是,从长远来看,我建议你将两个设置(主机和容器)集成到一个组合文件中,以摆脱这些问题。

相关问题