Table of Contents
Question content
Solution
Home Backend Development Golang Golang testcontainers, can't get network to work

Golang testcontainers, can't get network to work

Feb 14, 2024 pm 01:30 PM

Golang testcontainers,无法使网络工作

php editor strawberry encountered a problem when using Golang testcontainers, that is, it could not make the network work properly. Golang testcontainers is a tool for running containers in tests, which helps developers quickly start and destroy containers in a test environment. However, in actual use, PHP editor Strawberry found that the network function could not be used normally in the container, which caused certain problems in the test. Next, we will explore the solution to this problem together.

Question content

I'm trying to create some tests in my microservice, I want to create a network to attach my database test container (postgres) and my microservice test container to this network. No matter what I try, I can't get my microservice to connect to the database. My microservice is golang using Fiber and Gorm. I try to connect to the database in the db.go configuration file like this:

func SetupDB(port string, host string) *gorm.DB {

    dsn := "host=" + host + " user=postgres password=password dbname=prescription port=" + port + " sslmode=disable"

    db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})

    if err != nil {
        panic("error connecting to database")
    }

    db.AutoMigrate(&model.Prescription{})

    return db
}
Copy after login

This is what my test container looks like:

prescriptionDBContainer, err := testcontainers.GenericContainer(context.Background(), testcontainers.GenericContainerRequest{
        ContainerRequest: testcontainers.ContainerRequest{
            Image:        "postgres",
            ExposedPorts: []string{postgresPort.Port()},
            Env: map[string]string{
                "POSTGRES_USER":     "postgres",
                "POSTGRES_PASSWORD": "password",
                "POSTGRES_DB":       "prescription",
            },
            Networks: []string{network.Name},
            NetworkAliases: map[string][]string{
                network.Name: {"db-network"},
            },
            WaitingFor: wait.ForAll(
                wait.ForLog("database system is ready to accept connections"),
                wait.ForListeningPort(postgresPort),
            ),
        },
        Started: true,
    })
Copy after login
prescriptionContainer, err := testcontainers.GenericContainer(context.Background(), testcontainers.GenericContainerRequest{
        ContainerRequest: testcontainers.ContainerRequest{
            FromDockerfile: testcontainers.FromDockerfile{Context: "../../../../prescription"},
            Networks:       []string{network.Name},
            NetworkAliases: map[string][]string{
                network.Name: {"db-network"},
            },
            Env: map[string]string{
                "POSTGRES_USER":     "postgres",
                "POSTGRES_PASSWORD": "password",
                "POSTGRES_DB":       "prescription",
                "HOST":              prescriptionDBHost,
                "DB_PORT":           prescriptionDBPort.Port(),
            },
            ExposedPorts: []string{pMicroPort.Port()},
            WaitingFor:   wait.ForListeningPort("8080"),
        },
        Started: true,
    })
Copy after login

Maybe it's because I simply don't understand what's going on during the network connection process in docker, but I'm really lost, when I set up the environment for HOST and DB_PORT (I've tried every combination under the sun), It refuses to connect to the database microservice

In the test container of the microservice I tried:

"HOST":              prescriptionDBHost,
"DB_PORT":           prescriptionDBPort.Port(),
Copy after login

The extraction method of prescriptionDBHost is:

prescriptionDBHost, err := prescriptionDBContainer.Name(context.Background())
Copy after login

Results in error message:

failed to initialize database, got error failed to connect to `host=/stoic_heyrovsky user=postgres database=prescription`: dial error (dial unix /stoic_heyrovsky/.s.PGSQL.53802: connect: no such file or directory)
panic: error connecting to database
Copy after login

Then I tried removing the "/" from the hostname, for example:

"HOST":              strings.Trim(prescriptionDBHost,"/"),
"DB_PORT":           prescriptionDBPort.Port(),
Copy after login

I also tried:

"HOST":              "localhost",
"DB_PORT":           prescriptionDBPort.Port(),
Copy after login
"HOST":              "127.0.0.1",
"DB_PORT":           prescriptionDBPort.Port(),
Copy after login
prescriptionDBHost, err := prescriptionDBContainer.ContainerIP(context.Background())

"HOST":              prescriptionDBHost,
"DB_PORT":           prescriptionDBPort.Port(),
Copy after login

The last 4 examples here will all result in some kind of dialup TCP error, for example:

failed to initialize database, got error failed to connect to `host=localhost user=postgres database=prescription`: dial error (dial tcp [::1]:53921: connect: cannot assign requested address)
Copy after login

I also debugged and stopped after creating the database container in testcontainer, then went to my microservice and hardcoded a connection to the container using DB_HOST=localhost and port= and it worked, so I'm really lost on what's going on What happened was wrong. The only thing I can think of is that the microservice container is not connected to the network before trying to connect to the database? I did a docker network check and I can see that the database container is attached, but the microservice never attaches (but maybe that's just for other reasons?).

Solution

You can do this:

prescriptionDBContainer, err := testcontainers.GenericContainer(context.Background(), testcontainers.GenericContainerRequest{
    ContainerRequest: testcontainers.ContainerRequest{
        Image:        "postgres",
        ExposedPorts: []string{"5432/tcp"},
        Env: map[string]string{
            "POSTGRES_USER":     "postgres",
            "POSTGRES_PASSWORD": "password",
            "POSTGRES_DB":       "prescription",
        },
        Networks:       []string{networkName},
        NetworkAliases: map[string][]string{networkName: []string{"postgres"}},
        WaitingFor: wait.ForAll(
            wait.ForLog("database system is ready to accept connections"),
            wait.ForListeningPort("5432/tcp"),
        ),
    },
    Started: true,
})
if err != nil {
    t.Fatal(err)
}

prescriptionContainer, err := testcontainers.GenericContainer(context.Background(), testcontainers.GenericContainerRequest{
    ContainerRequest: testcontainers.ContainerRequest{
        FromDockerfile: testcontainers.FromDockerfile{Context: "./testapp"},
        ExposedPorts:   []string{"8080/tcp"},
        Networks:       []string{networkName},
        NetworkAliases: map[string][]string{networkName: []string{"blah"}},
        Env: map[string]string{
            "DATABASE_URL": "postgres://postgres:password@postgres:5432/prescription",
        },
        WaitingFor: wait.ForListeningPort("8080/tcp"),
    },
    Started: true,
})
Copy after login

Note how NetworkAliases are configured; in your code you set both to db-network However, I guess, this is due to a misunderstanding. This setting configures an alias that can refer to the container (in this example, I'm using postgres as the postgres container; this means that when connecting to HOST, according to the URL used in the example above , postgres will be postgres).

As an alternative, you can use port, err := prescription DBContainer.MappedPort(context.Background(), "5432/tcp") Get the port exposed on the host and then connect to the port host.docker.internal port.Port(). This method is often used when the application under test is running on the host rather than in a container (but in this case In this case, you will connect to localhost and use the report returned from MappedPort()).

The above is the detailed content of Golang testcontainers, can't get network to work. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the vulnerabilities of Debian OpenSSL What are the vulnerabilities of Debian OpenSSL Apr 02, 2025 am 07:30 AM

OpenSSL, as an open source library widely used in secure communications, provides encryption algorithms, keys and certificate management functions. However, there are some known security vulnerabilities in its historical version, some of which are extremely harmful. This article will focus on common vulnerabilities and response measures for OpenSSL in Debian systems. DebianOpenSSL known vulnerabilities: OpenSSL has experienced several serious vulnerabilities, such as: Heart Bleeding Vulnerability (CVE-2014-0160): This vulnerability affects OpenSSL 1.0.1 to 1.0.1f and 1.0.2 to 1.0.2 beta versions. An attacker can use this vulnerability to unauthorized read sensitive information on the server, including encryption keys, etc.

How do you use the pprof tool to analyze Go performance? How do you use the pprof tool to analyze Go performance? Mar 21, 2025 pm 06:37 PM

The article explains how to use the pprof tool for analyzing Go performance, including enabling profiling, collecting data, and identifying common bottlenecks like CPU and memory issues.Character count: 159

How do you write unit tests in Go? How do you write unit tests in Go? Mar 21, 2025 pm 06:34 PM

The article discusses writing unit tests in Go, covering best practices, mocking techniques, and tools for efficient test management.

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

What is the go fmt command and why is it important? What is the go fmt command and why is it important? Mar 20, 2025 pm 04:21 PM

The article discusses the go fmt command in Go programming, which formats code to adhere to official style guidelines. It highlights the importance of go fmt for maintaining code consistency, readability, and reducing style debates. Best practices fo

PostgreSQL monitoring method under Debian PostgreSQL monitoring method under Debian Apr 02, 2025 am 07:27 AM

This article introduces a variety of methods and tools to monitor PostgreSQL databases under the Debian system, helping you to fully grasp database performance monitoring. 1. Use PostgreSQL to build-in monitoring view PostgreSQL itself provides multiple views for monitoring database activities: pg_stat_activity: displays database activities in real time, including connections, queries, transactions and other information. pg_stat_replication: Monitors replication status, especially suitable for stream replication clusters. pg_stat_database: Provides database statistics, such as database size, transaction commit/rollback times and other key indicators. 2. Use log analysis tool pgBadg

Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Apr 02, 2025 am 09:12 AM

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

See all articles