title: dial error (dial tcp 172.18.0.2:8001: connect: connection refused) when trying to run go program in one container that connects to postgres in another
body: <p>I currently have two docker containers set up on my PC where one is a PostgreSQL container created with docker compose and the other contains go code to initialize a table within the PostgreSQL db. Docker compose works perfectly in creating the container/db (i am to log into it through psql outside of the container) and the go code itself runs properly outside of a container (creates tables). The problem arises when I try to run the code from inside its own container whether I try to connect to a local database or the containerized one. Both cases lead to the dial error in the title.</p>
  <p>I'm just a beginner when it comes to docker so I know its most likely a problem on my end but here are the contents of my dockerfile:</p>
  <pre><code>FROM golang:alpine AS builder 
  
  #adding needed env variables 
  ENV GO111MODULE=on \
      CGO_ENABLED=0 \
      GOOS=linux \
      GOARCH=amd64 
      
  #move to /build 
  WORKDIR /build 
  
  #copy dependancies 
  COPY go.mod . 
  COPY go.sum . 
  RUN go mod download 
  
  #add code to container 
  COPY . .
  
  #build app 
  RUN go build -o main . 
  
  # Move to /dist directory as the place for resulting binary folder
  WORKDIR /dist
  
  # Copy binary from build to main folder
  RUN cp /build/main .
  
  # Build a small image
  FROM scratch
  
  COPY --from=builder /dist/main /
  
  ENV DATABASE_URL=postgres://short:password@test:8001/shorturl
      #change database url variable to match your needs 
      
  # Command to run
  ENTRYPOINT [&quot;/main&quot;]
  </code></pre>
  <p>and the contents of the docker-compose.yml file:</p>
  <pre><code>version: '3'
  services:
    database:
      container_name: test
      image: &quot;postgres&quot; # use latest official postgres version
      env_file:
        - ./db/database.env # configure postgres
      volumes:
        - database-data:/var/lib/postgresql/data/ # persist data even if container shuts down
      ports:
          - &quot;8001:5432&quot; 
    backend: 
      build: . 
  volumes:
    database-data: 
  </code></pre>
  <p>The code itself exists in the following directory structure:</p>
  <pre><code>/project/
      ./db/ 
           db.go 
           database.env
      main.go 
      go.mod 
      go.sum 
      Dockerfile 
      docker-compose.yml 
  </code></pre>
  <p>db.go contains:</p>
  <pre><code>package db
  import (
      &quot;context&quot;
      &quot;fmt&quot;
      &quot;os&quot;
  
      &quot;github.com/jackc/pgx/v4/pgxpool&quot;
  )
  
  //InitDb creates a connection to our postgres db and populates it
  func InitDb(dbURL string) *pgxpool.Pool {
      connPool, err := pgxpool.Connect(context.Background(), dbURL)
      if err != nil {
          fmt.Fprintf(os.Stderr, &quot;Unable to connect to database: %v\n&quot;, err)
          os.Exit(1)
      }
      return connPool
  }
  
  //PopulateDb populates our databse with the appropiate tables i.e id, url, base64 encoding, visited, visit count
  func PopulateDb(db *pgxpool.Pool) {
      _, err := db.Exec(context.Background(), &quot;create table if not exists shortener (id serial primary key not null, url varchar not null, visited boolean default false, count integer default 0);&quot;)
      if err != nil {
          fmt.Fprintf(os.Stderr, &quot;Unable to create users table: %v\n&quot;, err)
          os.Exit(1)
      }
      fmt.Printf(&quot;Successfully created users table\n&quot;)
  }
  </code></pre>
  <p>database.env which is used to generate the database with docker-compose contains:</p>
  <pre><code>POSTGRES_USER=short
  POSTGRES_PASSWORD=password
  POSTGRES_DB=shorturl 
  </code></pre>
  <p>main.go contains:</p>
  <pre><code>package main
  
  import (
      &quot;fmt&quot;
      &quot;os&quot;
      &quot;project/db&quot;
  )
  
  func main() {
      /*
          set databse url in this format from root directory
          DATABASE_URL=postgres://user:password@host:port/database
      */
      dbURL := os.Getenv(&quot;DATABASE_URL&quot;)
      conn := db.InitDb(dbURL)
      db.PopulateDb(conn)
      defer conn.Close()
  }
  </code></pre>
  <p>As I mentioned before running all of this outside of any containers works and populates the database and docker-compose successfully creates an instance of postgres that I can connect to locally.</p>
  <p>What I cant do is connect to the containerized postgres through my code (ran locally or in a container) or connect to a local database from the containerized version of my code. All of those result in some variation of this error:</p>
  <pre><code>Unable to connect to database: failed to connect to `host=container_name user=short database=shorturl`: dial error (dial tcp 172.18.0.2:8001: connect: connection refused) 
  </code></pre>
  <p>I'm curious about what I might be doing wrong in my code and/or with docker and hoping someone can run it on their end and reproduce my issues/find whats wrong.</p>