登录
首页 >  Golang >  Go问答

当 Go 客户端和 REST API 在同一 Docker 容器中时,无法建立连接

来源:stackoverflow

时间:2024-02-12 20:03:24 138浏览 收藏

亲爱的编程学习爱好者,如果你点开了这篇文章,说明你对《当 Go 客户端和 REST API 在同一 Docker 容器中时,无法建立连接》很感兴趣。本篇文章就来给大家详细解析一下,主要介绍一下,希望所有认真读完的童鞋们,都有实质性的提高。

问题内容

我对 docker 和 go 非常陌生。我在 go 中创建了一个客户端应用程序来测试 rest api。该 api 作为 docker 镜像的一部分提供。我应该在客户端应用程序中添加测试,并使我的客户端应用程序作为同一 docker-compose.yml 的一部分可用。

在本地,我可以运行 go test -v ./... -cover 并且所有测试都可以访问 api http://localhost:8095/v1/organization/accounts

当我运行 docker compose up 时,我在下面的屏幕截图中收到错误。

客户端应用程序无法访问容器内的 api url,但可以从我的主机笔记本电脑访问它

任何建议对于如何完成这项工作都会非常有帮助。我对此任务的说明是,在客户端应用程序中针对 api 端点编写的测试应作为 docker-compose.yml 文件的一部分运行。

我为客户端应用程序添加了新的 dockerfile,如下所示,然后将其包含在 docker-compose.yml 中。

dockerfile:

from golang:alpine

env go111module=on \
    cgo_enabled=0 \
    goos=linux \
    goarch=amd64

workdir /build

# copy and download dependency using go mod
copy go.mod .
run go mod download

copy . .

workdir /build/accountsapi

run go test ./... -cover

docker-compose.yml

version: '3'

services:
  # app service
  app:
    # configuration for building the docker image for the service
    build:
      context: . 
      dockerfile: dockerfile
    restart: unless-stopped
    depends_on: 
      - accountapi
  accountapi:
    image: cooltech/accountapi:v1.0.0-50-g48935
    restart: on-failure
    depends_on:
      - postgresql
      - vault
    environment:
  - psql_user=root
  - psql_password=password
  - psql_host=postgresql
  - psql_port=5432
  - stack_name=accountapi
  - database-host=postgresql
  - database-ssl-mode=disable
  - database-username=api_user
  - database-password=xxx
ports:
  - 8095:8080
...more services

这里是示例测试和实际方法

func TestGetAccountByIdExpectsNoAccount(t *testing.T) { 
    // act
    resp := GetAccountById(getUUID())

    defer resp.Body.Close()

    //assert
    if status := resp.StatusCode; status != http.StatusNotFound {
        t.Errorf("handler returned wrong status code: got %v want %v",
            status, http.StatusOK)
    }
}

const Baseurl = "http://localhost:8095/v1/organisation/accounts"
func GetAccountById(id string) *http.Response {

    var url = fmt.Sprintf("%s/%s", Baseurl, id)
    resp, err := http.Get(url)
    if err != nil {
        fmt.Println(err)
    }

    return resp
}

正确答案


最后,在@rengas在评论中指出我试图在我的api服务启动之前运行测试(这是docker-compose的一部分)之后,我发现了这个问题。所以我删除了 go test -v ./... 来自我的 dockerfile 并将其添加为 docker-compose 的一部分,现在如下所示

accountapitesting:
    build:
      context: . 
      dockerfile: Dockerfile
    restart: on-failure
    command: go test -v ./...
    depends_on: 
      - accountapi

到这里,我们也就讲完了《当 Go 客户端和 REST API 在同一 Docker 容器中时,无法建立连接》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>