Create internal connection between React and Laravel in Docker containers on server

Viewed 757

I am using a React app as frontend and a Laravel app for backend. These two are connected with each other through Laravel Sanctum APIs. The whole environment is deployed on the server using Docker, frontend & backend being separate containers, but connected with network: someNetwork

The API call is done from the frontend using the URL HTTP://myserverip:8000 - this is working, but I would like to close the 8000 port (externally) and just keep open the 3000 port where the frontend is working. Now when I'm closing the 8000 port (with firewall), and trying to make API request from frontend I get a network error.

The question is, how to make the API request internally so I can keep only 3000 open, do I need some kind of redirection inside the .conf file of the nginx? This is my .conf 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;
    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass app:9000;
        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;
    }
}

Thanks, any hint would be appreciated.

1 Answers

What you are trying to do will never work.

ReactJS (I guess thats what you mean by ReactApp) should be "build" before used in production. The result will be a build folder with a bunch of static files.

These files can be deployed / serverd using NGINX. The API-Calls from ReactJS (your Frontend App) will always come from outside of your network as the client / customer will not be part of your Docker NAT network (I guess).

I would use NGINX as a Webserver for your ReactApp (ReactJS Build) as well as a reverse Proxy / Proxy for your Laravel Backend.

Something like:

server {
  listen 443 ssl;
  server_name example.com
  .....
  root /path/to/your/reactapp/static/files;
 
  location / {
   try_files $uri /index.html;
  }
}

server {
  listen 443 ssl;
  server_name api.example.com;
  
  ...all the laravel PHP config here

}

if you can not or want not create a subdomain for your API use a location

server {
  listen 443 ssl;
  server_name example.com
  .....
  root /path/to/your/reactapp/static/files;
 
  location / {
   try_files $uri /index.html;

  }
  
  location /api/ {
    Do your Laravel config here (use nested locations for handling the php files)
    Or do a `proxy_pass` and configure an internal server (listen `8000`) and do      not expose it.
  }

}

Related