Docker-Compose API调用和端点容器化

Using docker-compose I've got multiple containers running - one of them is the profiler container that calls an API, the other container apiconnection should be receiving the call and sending information back. However when I run the compose file it always returns Get http://apiconnection:8080/maccaption: dial tcp: lookup apiconnection on no such host on the Profiler container at the http.DefaultClient.Do line.

This is a sample of my compose file:

 image: apiconnection:1.0
  - "8080:8080"
  - maccaptionNet
  image: profiler:1.0
   - maccaptionNet
   - "apiConnection"

I'm calling the api in my profiler image like so - it's erroring on DefaultClient:

url := "http://apiconnection:8080/maccaption"

req, err := http.NewRequest("GET", url, nil)
if err != nil {

res, err := http.DefaultClient.Do(req)
if err != nil {
    fmt.Println("Line 27")

body, err := ioutil.ReadAll(res.Body)
if err != nil {
    fmt.Println("Line 33")

If I modify the url := "http://apiconnection:8080/maccaption" to look at localhost like this url := "http://localhost:8080/maccaption" it changes to connect refused, but I don't think I should be looking at localhost, I need to look at the Docker container don't I?

I'm setting the url as a connection to the docker container and using the ports I've assigned in the docker-compose file. and receiving the request in my apiconnection image like this:

    r := mux.NewRouter()

r.HandleFunc("/maccaption", handleMaccaption).Methods("GET")

http.ListenAndServe(":8080", r)

All it should be doing now is starting up and making a single request to prove that it is working and returning some json information. This code works outside of docker, replacing the container name in the url variable with localhost. But I cannot get it running within docker.

I've looked at these other sources for assistance but to no avail: how to call api endpoint inside docker container? Making a REST Call to Endpoint in Dockers Docker-compose internal communication using endpoints

Any pointers would be greatly appreciated - thank you!

**EDIT - to fix my wonky code formatting

dongpingwu8378 感谢您拨出@DavidMaze-非常感谢!它通过一条新的错误消息使我走上了正确的轨道。我已经用实际问题修改了原始问题。
一年多之前 回复
duanpo6079 “我忽略了错误返回,然后我的程序惊慌了”显然不是惯用的Go。您需要捕获错误返回。该错误信息可能包含一些有用的信息。
一年多之前 回复


对于以后尝试进行此类操作的任何人:上面的代码实际上是有效的。 但是我出了问题的地方是在我的 url:=“ http:// apiconnection:8080 / maccaption” </ code>中,我指的是映像名称,而不是我在docker中定义的服务名称。 -撰写。 </ p>

更改url以查看服务名称而不是图像名称可以解决此问题,现在我可以在dockerized环境中进行API调用。 </ p>
</ div>



For anyone who's attempting to do something like this in the future: the above code actually does work. But where I was going wrong was that in my url := "http://apiconnection:8080/maccaption" I was referring to the image name instead of the service name I've defined in the docker-compose.

changing the url to look at the service name instead of the image name corrected the issue and I'm now able to make API calls within my dockerized environment.

Csdn user default icon