elp
elp

Reputation: 870

Can't reach containerized service behind nginx container

I got this architecture and it is almost working.

But something seems to be wrong with my config. The nginx and the container are on the same network.

Architecture:

                                             [replica 2]
                                            /
[incoming traffic] -> [nginx] -> [service a]
                                            \
                                             [replica 1]

docker-compose.yml

version: "3"
services:
  articleservice:
    image: elps/articleservice:1.1.0.5
    deploy:
      replicas: 2
      restart_policy:
        condition: on-failure
      placement:
        constraints:
          - node.role == manager
    ports:
      - "8080:8080"
    environment:
      - MYSQL_HOST=192.168.178.96
      - MYSQL_DB=catalog
      - MYSQL_USER=root
      - MYSQL_PASSWORD=root
    networks:
      - webnet     

  nginx-default:
    image: nginx
    deploy:
      restart_policy:
        condition: on-failure
      placement:
        constraints:
          - node.role == manager
    ports:
      - "80:80"
    networks:
      - webnet

networks:
  webnet:

nginx-config

server {
  listen 80;
  listen [::]:80;

  server_name example.com;

  location /article {
      proxy_pass http://articleservice:8080/; 
  }
}

Upvotes: 1

Views: 63

Answers (2)

victortv
victortv

Reputation: 8982

You should create a volume in the nginx-default service so it can use the nginx.conf file.

Example:

  nginx-default:
    image: nginx
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf
    deploy:
      restart_policy:
        condition: on-failure
      placement:
        constraints:
          - node.role == manager
    ports:
      - "80:80"
    networks:
      - webnet

Another problem is that if you access the url example.com/article/someMethod it will translate to articleservice:8080/article/someMethod
To remove the prefix "/article" part you can rewrite it:

  location /article {
      proxy_pass http://articleservice:8080/; 
      rewrite ^/article(.*)$ $1 break;
  }

Now you can use curl example.com/article/someMethod to use the articleService

Upvotes: 0

elp
elp

Reputation: 870

Once again, I forgot to add the host in the header.

Solution:

curl -H 'host: example.com' http://articleservice:8080/somemethod

Upvotes: 1

Related Questions