Ashwani
Ashwani

Reputation: 545

Nginx Request redirection one container to another

I am running two centos docker container using following compose file-

version: "2"
services:
  nginx:
    build:
      context: ./docker-build
      dockerfile: Dockerfile.nginx
    restart: always
    ports:
      - "8080:8080"
    command: "/usr/sbin/nginx"
    volumes:
      - ~/my-dir:/my-dir

  data:
    build:
      context: ./docker-build
      dockerfile: Dockerfile.data
    restart: always
    ports:
      - "8081:8081"
    command: "/usr/sbin/nginx"
    volumes:
     - ~/my-dir-1:/my-dir-1

and I have installed the nginx using Dockerfile in both containers to access specific directories. Trying to redirect request http://host-IP:8080/my-data/ to the data container using nginx. Below is my Nginx configuration for nginx container

/etc/nginx/conf.d/default.conf

server {
    listen 8080;

  location / {
       root   /my-dir/;
       index  index.html index.htm;
       }

}

I am able to access my-dir directory using http://host-IP:8080 URL and my-dir-1 using http://host-IP:8081 URL, how can I configure Nginx to redirect request on data container using http://host-IP:8080/my-data URL

Upvotes: 0

Views: 1864

Answers (3)

Divek John
Divek John

Reputation: 755

If your looking for WebSocket conf here it is :

  server {
        server_name  _;
    
        location /ws {
            proxy_pass http://localhost:8888;
            # this is the key to WebSocket
            proxy_http_version  1.1;
            proxy_set_header    Upgrade $http_upgrade;
            proxy_set_header    Connection "upgrade";
            proxy_set_header    Host $http_host;
            proxy_set_header    X-Real-IP $remote_addr;
        }
    
        location / {
            proxy_pass http://localhost:8889;
        }
    }

Happy coding :)

Upvotes: 0

pvrforpranavvr
pvrforpranavvr

Reputation: 2948

nginx.conf file

http {

 server {

   listen 80;

   location /api {

     proxy_pass http://<SERVICE_NAME>:8080/my-api/;

   }

   location /web {

     proxy_pass http://<SERVICE_NAME>:80/my-web-app/;

   }

 }

}

events { worker_connections 1024; }

NB: Here /my-api and /my-web-app are the application context path . The SERVICE_NAME is the name specified for each service in docker-compose.yml file.

Dockerfile for nginx

FROM nginx
RUN rm /etc/nginx/conf.d/default.conf
COPY nginx.conf /etc/nginx
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

Now access urls via

Upvotes: 0

jhernandez
jhernandez

Reputation: 937

I don't really get the use case of your app and why are you doing this way.

But you can do this with a proxy, untested code look for the docs but something like this.

http {
  upstream data_container {
    server data:8081;
  }
  server {
    listen 8080;


    location / {
        root   /my-dir/;
        index  index.html index.htm;
    }
    location /my-data {
      proxy-pass http://data_container$request_uri;
    }
  }
}

Upvotes: 1

Related Questions