Home > OS >  NGINX configuration for multiple Docker containers
NGINX configuration for multiple Docker containers

Time:08-31

The system I'm working on consists of an SvelteKit app and a Flask App. Both are inside it's own docker container and a third one with an NGINX image.

The idea is that all requests that doesn't start with /api go to the SvelteKit app, and the ones that do go to the Flask app.

worker_processes 1;

events { worker_connections 1024; }

http {
    sendfile on;

    upstream backend {
        server backend:5002;
    }

    upstream frontend {
        server frontend:5001;
    }

    server {
        listen 80;

        location / {
            proxy_pass http://frontend;
            proxy_redirect     off;
            proxy_set_header   Host $host;
            proxy_set_header   X-Real-IP $remote_addr;
            proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header   X-Forwarded-Host $server_name;
        }
    }

    server {
        listen 80;

        location /api {
            proxy_pass http://backend;
            proxy_redirect     off;
            proxy_set_header   Host $host;
            proxy_set_header   X-Real-IP $remote_addr;
            proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header   X-Forwarded-Host $server_name;
        }
    }
}

After a lot of tries this is the config that is closest to the result I need but /api still goes to the SvelteKit app. So as I see it, I don't understand anything about how Nginx works.

This is the docker ps output:

CONTAINER ID   IMAGE                  COMMAND                  CREATED          STATUS         PORTS                                       NAMES
02e5f32f3b5f   stopssis_v2_nginx      "/docker-entrypoint.…"   7 minutes ago    Up 6 minutes   0.0.0.0:80->80/tcp, :::80->80/tcp           nginx
4ebe13b534db   stopssis_v2_frontend   "docker-entrypoint.s…"   26 minutes ago   Up 6 minutes   0.0.0.0:5001->5001/tcp, :::5001->5001/tcp   frontend
94345bfd5123   stopssis_v2_backend    "python ./app/run.py"    26 minutes ago   Up 6 minutes   0.0.0.0:5002->5002/tcp, :::5002->5002/tcp   backend

Also, any good resource that explains nginx visually?

CodePudding user response:

Maybe take a look at the nginx beginners guide:

Generally, the configuration file may include several server blocks distinguished by ports on which they listen to and by server names. Once nginx decides which server processes a request, it tests the URI specified in the request’s header against the parameters of the location directives defined inside the server block.

Meaning that you should not have two separate server objects for routing traffic to different endpoints based on the path of the request. But instead you should put both location blocks inside the same server block, as they refer to the same servername and port.

  • Related