I have a server in one docker container (port 5044) and client in other docker container (port 4545). I want to send POST request from client to server but i get an error message "Post "http://127.0.0.1:5044/check": dial tcp 127.0.0.1:5044: connect: connection refused".
json, err := json.Marshal(x)
if err != nil {
log.Fatal(err)
}
resp, err := http.Post("http://127.0.0.1:5044/check", "application/json", bytes.NewBuffer(json))
//Handle Error
if err != nil {
log.Fatalf("An Error Occured %v", err)
}
defer resp.Body.Close()
//Read the response body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalln(err)
}
return string(body)
I can send post request using postman and everything is ok.
I tried to connect to test internet service (https://ptsv2.com/) and it works as well. It seems like golang doesnt want to conenct to the local server form docker :/
3
Answers
your docker app is accessible from it’s "external port" with Postman
But to allow them to communicate together they need to be on the same network
the easiest way to do it is to use a docker-compose (instead of manually creating the neworks) official link
your network is declared at the end of the line, and it’s linked to both your Docker service via the tag networks (below ports)
The best practice to connect to the docker container is by using the container name e.g.
http://app_one:5044/check
, you can find the container name by using thedocker ps
command. in order to connect with the container name, all containers have to be in the same network.But if you want to use IP this is the way.
Each container has a different IP address, in order to connect from one container to another you need to know the container IP address that you want to connect. 127.0.0.1 is not the container IP, it’s the host IP.
you can to find the IP address of the container by this command,
docker inspect your_container_name
you will see the IP in networking sectionin my example
172.18.0.37
is my container IP address. so I need to use that by to communicate e.g.http://172.18.0.37:5044/check
be aware that IPAddress if the container can change when you restart the container so it’s better to use container name
Find your service name from your
docker-compose.yml
file for the server and replace this:with this: