Reputation: 53
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.
Upvotes: 1
Views: 2478
Reputation: 2679
This is how to use bridge driver network in docker to communicate between two containers.
The github sample in .net core 2.2 is here
version: '3.4'
services:
eventstoresample:
image: eventstoresample
build:
context: .
dockerfile: EventStoreSample/Dockerfile
networks:
clusternetwork:
ipv4_address: 172.16.0.12
eventstore:
image: eventstore/eventstore
environment:
- EVENTSTORE_INT_IP=172.16.0.13
- EVENTSTORE_EXT_HTTP_PORT=2113
- EVENTSTORE_EXT_TCP_PORT=1113
- EVENTSTORE_EXT_HTTP_PREFIXES=http://*:2113/
ports:
- "1113:1113"
- "2113:2113"
networks:
clusternetwork:
ipv4_address: 172.16.0.13
networks:
clusternetwork:
driver: bridge
ipam:
driver: default
config:
- subnet: 172.16.0.0/24
Upvotes: 0
Reputation: 11367
let's say you run the first container with the following command:
docker run -d --name my_service web_api_image
so you can use the --link
flag to run the second:
docker run -d -P --name web --link my_service:my_service website_image
then, within website container you can refer to the web api using my_service hostname.
please note:
--link
is deprecated.
you can also use docker-compose
:
version: "2"
services:
web_api:
image: web_api_image
container_name: web_api
ports:
- "8000:8000"
expose:
- "8000"
website:
image: website_image
container_name: website
ports:
- "80:80"
links:
- "web_api:web_api"
replace image names and run with docker-compose up
Upvotes: 1
Reputation: 10447
You can use docker-compose
, since all containers within the same compose file are within the same network by default and can call each other using their service name.
However, if you are using docker run
you can specify hostname using -h
flag. Example: docker run -h test.example.com -it ubuntu /bin/bash
.
I would recommend you to look into aliases of docker-compose. Further ahead, you and your customer, both can use a env_file
variable to specify values for variables.
Upvotes: 0