Home > Software design >  Golang POST request from one to another docker container
Golang POST request from one to another docker container

Time:10-14

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 :/

CodePudding user response:

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

version: '3'
services:

first:
  build:
    context: ./your-first-app
    dockerfile: Dockerfile
  ports:
    - '1800:1800'
  networks:
    my-network:

second:
  build:
    context: ./your-second-app
    dockerfile: Dockerfile
  ports:
    - '1801:1801'
  networks:
    my-network:

networks:
  my-network:

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)

CodePudding user response:

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 section

"Networks": {
  "bridge_network": {
    "Gateway": "172.18.0.1",
    "IPAddress": "172.18.0.37",
    "IPPrefixLen": 16,
    "IPv6Gateway": "",
    "GlobalIPv6Address": "",
    "GlobalIPv6PrefixLen": 0,
  }
}

in 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

  • Related