user5558501
user5558501

Reputation:

Node.JS proxy with Nginx and Docker

I have a docker container with nodejs and I have a docker container with nginx.

I have told my angular to use ec2-xxx:8888/api to use the api's. Because I ran my nodejs container with:

docker run -d -p 8888:8888 --name nodejs localhost:5000/test/node-js-image:1

So I mapped the 8888 of my docker on my amazon. So this is working. My app.config.js contains:

URL: 'http://ec2...',
      PORT: '8888',

I can see my api's on ec2:8888/api But it's not save to make your api accessible with the server. So I would like to run my nodejs like this:

docker run -d --name nodejs localhost:5000/test/node-js-image:1

So without mapping the container port on the port of my amazon. But I still need to access the nodejs container from my nginx container.

How can I do this? I tried in my nginx.conf:

http {    
        upstream node-app {
              least_conn;
              server nodejs:8888 weight=10 max_fails=3 fail_timeout=30s;

        }

        server {
              listen 80;

              location / {
                alias /usr/share/nginx/html/dist/;
                index index.html;
              }

              location /api {
                proxy_pass http://node-app;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection 'upgrade';
                proxy_set_header Host $host;
                proxy_cache_bypass $http_upgrade;
              }
        }
}

But this isn't working. I only see HTML (no CSS) and it's not possible to connect with the nodeJS container.

Upvotes: 1

Views: 2797

Answers (1)

michaelbahr
michaelbahr

Reputation: 4973

Assuming both containers run on the same machine, Docker's legacy container links are one possibility. Networking is the new way to go.

Start your nodejs container with

docker run -d --name nodejs --expose 8888 <YOUR_NODEJS_IMAGE>

In contrary to -p ... the option --expose ... makes your container only visible to linked containers.

Start your nginx container with the link to nodejs:

docker run -d --name nginx --link nodejs <YOUR_NGINX_IMAGE>

In order to access the nodejs docker container from your nginx docker container you must use environment variables injected by docker. This gist gives an example on how to do that.

Upvotes: 1

Related Questions