Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

internal and external network with docker-compose?

Suppose I have 2 docker containers: (A) shinyapptest is a front end that needs to communicate with (B) testapi and be accessible to the outside world.

To do this I created a network backend by running the following command:

docker network create -d bridge --subnet 192.168.0.0/24 --gateway 192.168.0.1 backend

Then shinyapptest makes its API calls to "http://192.168.0.1:3098.

To get everything up and running I wrote the following docker-compose:

version: '3.7'
services:
    shinyapptest:
      container_name: testshiny
      image: testshiny
      restart: unless-stopped
      networks:
            - frontend
            - backend
      ports:
          - 80:3838
    testapi:
      container_name: testapi
      image: testapi
      restart: unless-stopped
      networks:
            - backend
      ports:
          - 3098:3098
networks:
  backend:
    external:
      name: backend
  frontend:
    external:
      name: frontend

Is this right? Basically, I want (A) to have access to (B) and the outside world to have access to (A) but not (B). If this is right, how should I create the frontend network? Right now if I try to run docker-compose up I get this error because the network does not exist:

$ docker-compose up
ERROR: Network frontend declared as external, but could not be found. Please create the network manually using `docker network create frontend` and try again.
like image 408
Ignacio Avatar asked May 16 '26 11:05

Ignacio


1 Answers

Actually you don't even need the frontend network. If you attach the backend network to both containers they should be able to communicate with each other. Just like 2 computers on the same network.

If you don't want a container to be accessible from outside, simply don't map the respective port back into your host system. That will keep them isolated.

Currently your api has port 3098 exposed. If you remove that, but have the network attached to both containers you would be able to call port 3098 internally from your frontend container, but not from outside.

You may even use the assigned container name for internal communication, like so:

http://testapi:3098/...

I hope that helps.

like image 73
nullchimp Avatar answered May 18 '26 04:05

nullchimp