Access PostgreSQL Container Inside your VM from your Local Machine
We often come across designing such network, where we don’t want to keep our docker container in our local machine. Or sometimes, if we want to design a cloud network of our own, we may face such requirement. In this article I will try to explain how we can achieve this.
We will set up a PostgreSQL server on a docker container. The docker container will be on a Ubuntu based virtual machine. We will try to connect to the container from our local development machine, which will be running on Windows.
Assuming, we have Ubuntu installed on a VM, VM has docker installed and port 5432 is allowed for ingress and egress traffic.
To achieve this, we need to run the following command in our Ubuntu VM terminal.
Notice this command. I will explain the flags that I have been used in this command.
-p 5432:5432
Many of the readers might be already familiar with this flag. This flag is used to bind port. The port number at the left of the colon “:” is the port to be used inside the VM. The next 5432 is the port inside container, on which port the container is running.
-e POSTGRES_PASSWORD=123456
This argument is passed to set the password for the db user.
-e POSTGRES_HOST_AUTH_METHOD=trust
This parameter is used for avoiding the password authentication. If we set the value of this flag, then setting up the password is not required. This can be helpful when we want to connect from some IDE for database accessing. However, this is not a recommended approach.
— add-host=social_community:172.24.5.110
Here we are adding the host network, where we can bind our container. The value social_community will be used as the host name here. We have used this as hostname because we will create our database with this same name. This is not mandatory to use same name for both, but we just tried to avoid forgetting. The IP address is the VM’s own IP address. This can be found by running command ifconfig. This IP address will be used to connect to the db from outside.
Let’s create the database.
If we notice the above marked lines, we can understand that we have entered into the docker container in interactive mode, logged in to the postgres and created our database.
Now, let’s try to connect to the database from our IDE.
Notice that, when we provided the valid connection parameters, our connection is now successful.
That’s all for this article. If you think like there are more I could add, please feel free to let me know.