mywn9
mywn9

Reputation: 107

How to connect to Node API docker container from Angular Nginx container

I am currently working on an angular app using Rest API (Express, Nodejs) and Postgresql. Everything worked well when hosted on my local machine. After testing, I moved the images to Ubuntu server so the app can be hosted on an external port. I am able to access the angular frontend using the https://server-external-ip:80 but when trying to login, Nginx is not connecting to NodeApi. Here is my docker-compose file:

version: '3.0' 

services:

  db:
    image: postgres:9.6-alpine
    environment:
      POSTGRES_DB: myDb
      POSTGRES_PASSWORD: myPwd

    ports:
    - 5432:5432
    restart: always
    volumes:
    - ./postgres-data:/var/lib/postgresql/data
    networks:
    - my-network

  backend: # name of the second service
   image: myId/mynodeapi
   ports:
   - 3000:3000
   environment:
    POSTGRES_DB: myDb
    POSTGRES_PASSWORD: myPwd
    POSTGRES_PORT: 5432
    POSTGRES_HOST: db
   depends_on:
   - db
   networks:
   - my-network

   command: bash -c "sleep 20 && node server.js"

  myapp:
    image: myId/myangularapp
    ports:
    - "80:80"
    depends_on:
    - backend
    networks:
    - my-network

networks:
    my-network:

I am not sure what the apiUrl should be? I have tried the following and nothing worked:

  1. apiUrl: "http://backend:3000/api"
  2. apiUrl: "http://server-external-ip:3000/api"
  3. apiUrl: "http://server-internal-ip:3000/api"
  4. apiUrl: "http://localhost:3000/api"

Upvotes: 2

Views: 1881

Answers (1)

Hugo Lesta
Hugo Lesta

Reputation: 799

I think you should use the docker-compose service as a DNS. It seems you've several docker hosts/ports available, there are the following in your docker-compose structure:

  • db:5432
  • http://backend:3000
  • http://myapp

Make sure to use db as POSTGRES_DB in the environment part for backend service.

Take a look to my repo, I think is the best way to learn how a similar project works and how to build several apps with nginx, you also can check my docker-compose.yml, it uses several services and are proxied using nginx and are worked together.

On this link you’ll find a nginx/default.conf file and it contains several nginx upstream configuration please take a look at how I used docker-compose service references there as hosts.

Inside the client/ directory, I also have another nginx as a web server of a react.js project.

On server/ directory, it has a Node.js API, It connects to Redis and Postgres SQL database also built from docker-compose.yml.

If you need set or redirect traffic to /api you can use some ngnix config like this

I think this use case can be useful for you and other users!

Upvotes: 2

Related Questions