Vivek Viswanathan
Vivek Viswanathan Staff Engineer at Compass. Passionate about building software that pushes hardware to its limits!!

Start postgres on Ubuntu (using Docker)

Docker enables engineers to start the service with ease. In a tradition installation, developers had to go though the specific documentation and follow the step by step guide for installation. This takes typically 30-60 mins depending on the software. With docker, starting a service is all about pulling the docker file corresponding to the service and running it.

In this post, we discuss about starting the postgres service.

Pull the required docker file

Identify the required docker image to be pulled using the link: https://hub.docker.com/_/postgres

Now use the docker pull command to get the image:

$ docker pull postgres:<tag>

Note: If you receive the below output on issuing the above command, then it means the current runtime user isn't part of the docker group.

Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: 
Post http://%2Fvar%2Frun%2Fdocker.sock/v1.39/images/create?fromImage=postgres&tag=12: 
dial unix /var/run/docker.sock: connect: permission denied

Add the runtime user to the docker group (refer: https://docs.docker.com/install/linux/linux-postinstall) or run the command as root (i.e.) sudo docker pull postgres:<tag>

Run postgres service

Since we don't want to lose the data when the service stops, we have to mount a location for data storage before we start the postgres service using docker runtime:

mkdir -p $HOME/docker/volumes/postgres/data

Run the below command now to start the service:

$ docker run --rm  \
--name postgres-docker \
-e POSTGRES_PASSWORD=foo \
-e POSTGRES_USER=postgres \
-e POSTGRES_DB=snipshare \
-d \
-p 5432:5432 \
-v $HOME/docker/volumes/postgres/data:/var/lib/postgresql/data \
postgres

--rm: configures docker to cleanup when the container exits

--name: denotes the name for the container (used when listing the containers using the "docker ps" command)

-e: pass a set of environment variables that helps in configuring the container. POSTGRES_PASSWORD is for setting the admin password, POSTGRES_USER denotes the admin account name, POSTGRES_DB is the default database created

-d: instructs docker to launch the container in detached/background mode

-p: maps the port in localhost with that of the port inside the container

-v: mounts the volume in host to a specific location within the container

Now you can use tools like DBeaver to connect to the database using the provided username and password

Reference: https://hub.docker.com/_/postgres

comments powered by Disqus