Communicate between two containers

Hi all,

I’m newbie about docker and i need your help about communicate between containers.

I have two containers
Container 1: it is a Website and runs on port 80
Container 2: it is a web API of above Website and runs on port 8000

I install two containers in my Raspberry Pi. my RPi hostname is raspberrypi
I created two containers with --net=host so in my website, I can call my website via http://raspberrypi:8000/dosomething

but host name of RPi can be changed and I can’t recreate the website container with new API URL (for example: http://new_host_name:8000/dosomething) so my question is

is there any way to assign host name to a container so I can use it in other container ?
for example:
Container 2 uses “my_service” as its host name, so in Container 1 , I can use “http://my_service:8000/dosomething”. my customer can change their host name of RPI and I don’t need to update my codes.

Thanks and have nice day.

Hi,

I don’t think that this is a problem with docker, but rather your network setup and your webserver, that runs inside the container. Docker merely maps host ports to container ports. when you enter http://raspberrypi in your browser, that gets resolved on the browser’s host to an IP address and the HTTP GET request is sent to that IP. The webserver inside the container can then check what hostname / URL you actually called to process your request, but that has nothing to do with Docker.

You could consider using environment variables to dynamically update the hostname for the webserver config or just make the webserver reply to all requested hostnames.

Also not sure why you need the --net=host option.

1 Like

The best way to go about this is not to use --net=host but rather create a new docker network and connect both containers to that network. Containers on the same network can use the others container name to communicate with each other.

In your setup, you could do something like this:

docker network create mynet
docker run -d -p "80:80" --name web mywebimage
docker run -d --name my_service myapiimage

Then you can connect to your web service using the hostname of your raspberry pi and the web service can make calls to the API service with the URL http://my_service:8000/dosomething

Hope that helps.

2 Likes