Local Postgres Container Setting Up
This article has been done last couple of years, but it is still useful for developers who are during transition from old school services to the docker container world.
For example, we want to implement a service to access local Postgres DB. We can actually apt-get install
, yum install
or brew install
a postgres DB service. However, since we don’t want our local OS has heavy load to run Postgres all the time, using Docker to have a Postgres is a better choice.
Start running docker postgres
Let’s pull a postgres docker image
docker pull postgres
Then, run the postgres docker by mapping 5432 port to localhost.
docker run --rm \
--name pg-docker \
-e POSTGRES_PASSWORD=postgres \
-d \
-p 5432:5432 \
-v $HOME/docker/volumes/postgres:/var/lib/postgresql/data \
postgres
We can set password for user postgres
docker exec -it pg-docker bash
# psql -U postgres
postgres=# alter user postgres with PASSWORD 'postgres';
Golang test for DB Ping
We can write a simple go program to ping DB.
package main
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
)
const (
host = "localhost"
port = 5432
user = "postgres"
password = "postgres"
dbname = "my_db"
)
func main() {
psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
"password=%s dbname=%s sslmode=disable",
host, port, user, password, dbname)
db, err := sql.Open("postgres", psqlInfo)
if err != nil {
panic(err)
}
defer db.Close()
err = db.Ping()
if err != nil {
panic(err)
}
fmt.Println("DB is successful connected.")
}
We can also installed pgAdmin4 to access local docker hosted Postgres.