I have a project with Golang backend, PostgreSQL DB and Redis.
I need to init PostgreSQL DB with this SQL:
ALTER USER postgres WITH password '123';
CREATE TABLE users
(
username VARCHAR (200) PRIMARY KEY,
pass VARCHAR (50)
);
My Dockerfile is:
# syntax=docker/dockerfile:1
FROM postgres:latest AS go2
ENV POSTGRES_USER postgres
ENV POSTGRES_PASSWORD ''
ENV POSTGRES_DB postgres
EXPOSE 5432
ADD table.sql /docker-entrypoint-initdb.d/
FROM redis:latest AS go3
FROM golang:latest AS go
WORKDIR /app
COPY . .
RUN go build -o bin
ENTRYPOINT [ "/app/bin" ]
EXPOSE 8000
I build it with:
docker build . -t mycontainer
And run it with:
docker run -t mycontainer --network=bridge
But I get the following error:
[error] failed to initialize database, got error failed to connect to `host=172.17.0.2 user=postgres database=postgres`: dial error (dial tcp 172.17.0.2:5432: connect: connection refused)
My problems are:
- I can't connect to PostgreSQL DB
- I can't connect to Golang backend
I tried to run the container with this command:
docker run -t mycontainer --network=host
But the problems remain.
Update:
I created a docker-compose.yaml
file:
services:
db:
image: 'postgres:15.7'
restart: always
network_mode: bridge
volumes:
- './db/table.sql:/docker-entrypoint-initdb.d/init.sql'
ports:
- '5433:5432'
environment:
POSTGRES_DB: postgres
POSTGRES_USER: postgres
POSTGRES_PASSWORD: 123
redis:
image: 'redis:7.0.12'
network_mode: bridge
ports:
- '6380:6379'
backend:
build: ./backend
network_mode: bridge
ports:
- '8000:8089'
depends_on:
- db
My PostgreSQL DB and Redis work good and I can connect to them.
But when I run my backend container it throws this error:
[error] failed to initialize database, got error failed to connect to `host=127.0.0.1 user=postgres database=postgres`: dial error (dial tcp 127.0.0.1:5433: connect: connection refused)
docker run
only runs one container, and a container only runs one process. You might be looking for a tool like Docker Compose that can run the three containers in parallel. The Dockerfile you show only generates an image that runs the Go application, the data-store blocks get completely ignored.[error] failed to initialize database, got error failed to connect to
host=127.0.0.1 user=postgres database=postgres: dial error (dial tcp 127.0.0.1:5433: connect: connection refused)
localhost
almost always refer to the current container, not one of the other containers or the host system. Networking in Compose in the Docker documentation describes how to connect between containers.