Ch3shire
Ch3shire

Reputation: 1106

Redirecting ports with Nginx on Docker

I'm trying to build a simple Docker project, where you have few containers that are joined by one Nginx server. Basically it's simpler simulation for my fullstack project. I have the problem with redirecting one containers main port to path in another project.

Project contains two modules and one docker-compose.yml file. Expected behavior is to see one html website on http://localhost and the other on http://localhost/api . When I run project, I see expected result on http://localhost, but to get to the other site I need to go to http://localhost:4000. How to fix it?

Project files (source code here)

Module Client

index.html:

this is website you should see under /api

Dockerfile:

FROM node:14.2.0-alpine3.11 as build
WORKDIR /app
COPY . .
FROM nginx as runtime
COPY --from=build /app/ /usr/share/nginx/html
EXPOSE 80

Module Nginx

index.html:

<p>this is index file. You should be able to go to <a href="/api">/api route</a></p>

default.conf:

upstream client {
    server client:4000;
}

server {
    listen 80;

    location /api {
        proxy_pass http://client;
    }

    location / {
        root /usr/share/nginx/html;
    }
}

Dockerfile:

FROM nginx
COPY ./default.conf /etc/nginx/conf.d/default.conf 
COPY index.html /usr/share/nginx/html

Main directory

docker-compose.yml file:

version: "3"
services: 
    client: 
        build: Client
        ports:
            - 4000:80
    nginx:
        build: Nginx
        ports: 
            - 80:80
        restart: always
        depends_on: 
            - client

Upvotes: 1

Views: 3843

Answers (1)

Husein
Husein

Reputation: 550

There is 2 issues that I can find in your configuration:

  1. You are redirecting to port 4000 on the client container, which you do not need to do, as the port 4000 is only relevant for your host machine. So the upstream config should look like the following:
upstream client {
    server client;
}
  1. You are redirecting to /api on your client container, but your client container serves the content at /. You should change your default.conf to look like the following (mind the trailing slashes!):
upstream client {
    server client;
}

server {
    listen 80;

    location /api/ {
        proxy_pass http://client/;
    }

    location / {
        root /usr/share/nginx/html;
    }
}

With this configuration, you can enter http://localhost/api/ to get to your client container. If you want http://localhost/api to work, you could redirect /api to /api/ in your default.conf.

Upvotes: 3

Related Questions