Home > front end >  Docker nginx routing to API in other container
Docker nginx routing to API in other container

Time:02-05

i am going crazy not figuring this out..

I have a docker network created named isolated-network, and i have an nginx server and an API created in the network. Nginx on port 80 is exposed to the host so i can access it, but the API isnt. I know i could expose the API to the host too, but i'd like for it to be isolated and only accessible through nginx through say /api.

I have configured the Nginx at /api to route to http://my-api:8000, however i get 404 not found in return when accessing http://locahost/api. If i do 'docker exec -it nginx sh' and try to curl the same route http://my-api:8000 i get the expected response.

Is what i'm trying even possible? I have not found any example trying to do the same. If i can't route to http://my-api:8000, can i atleast send the API request to it and receive the response?

CodePudding user response:

in below i have an example that nginx will route traffic to php-fpm container

docker file:

FROM php:8.1-fpm

USER root

RUN mkdir -p /var/www/ && mkdir -p /home/www/.composer && chown www:www /var/www/html && chown www:www /home/www/.composer

#groupadd -g 1000 www && useradd -ms /bin/bash -G www -g 1000 www &&
RUN usermod -aG sudo www

RUN chown -R www /var/www

USER root

EXPOSE 9000

CMD ["php-fpm"]

docker compose file:

version: "3"

services:
webserver:
  image: nginx:1.21.6-alpine
  container_name: webserver
  restart: unless-stopped
  ports:
    - "80:80"
  volumes:
    - ./configfiles/nginx/conf-fpm:/etc/nginx/conf.d
php-fpm:
  image: php:8.1-fpm
  working_dir: /var/www
  stdin_open: true
  tty: true
  build:
  context: ./configfiles/php-fpm
  dockerfile: Dockerfile
  volumes:
    - ./src:/var/www

nginx config file

server {
    listen 80;
    index index.php index.html;
    error_log  /var/log/nginx/error.log;
    access_log /var/log/nginx/access.log;
    root /var/www/public;

    proxy_read_timeout 3600;
    proxy_connect_timeout 3600;
    proxy_send_timeout 3600;


    location ~ \.php$ {
          try_files $uri =404;
        fastcgi_split_path_info ^(. \.php)(/. )$;
        fastcgi_pass php-fpm:9000;
        fastcgi_read_timeout 3600;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
    }

    location / {

        try_files $uri $uri/ /index.php?$query_string;
        gzip_static on;
    }
 }
  • Related