Run a database in a Docker container
You can use Docker to run a database in a container as if it were a remote server, and test how your application interacts with it. This tutorial describes how to run a Docker container with a PostgreSQL server and connect to it using GoLand.
Before you begin:
Getting started in GoLand.
Pull a PostgreSQL server image
In the Services tool window, expand your Docker connection and select the Images node.
Image to pull In the Image to pull field, start typing
postgres
and select the necessary image repository. For example, selectpostgres
to pull the defaultpostgres:latest
image.Press Ctrl+Enter and wait until Docker pulls the image.
Run a container from the PostgreSQL server image
Expand the Images node, select the PostgreSQL server image, and click Create Container.
In the Create Docker Configuration dialog, do the following:
Click Modify options and select Randomly publish all exposed ports to publish all exposed container ports to the host interfaces. For a more secure setup, you will need to define specific port bindings, of course. However, in this tutorial, we assume that your local machine is secure enough and there is nothing important.
Click Modify options, select Environment variables, and configure environment variables that define the authentication settings for your PostgreSQL server. For the purposes of this tutorial, we can use Trust Authentication. Keep in mind, that this will enable anyone who can connect to the PostgreSQL server to access the database with any username of their choice. In the Environment variables field, click and add the
POSTGRES_HOST_AUTH_METHOD
variable with the valuetrust
.
Optionally, you can specify custom names for the configuration and the container.
Connect to the PostgreSQL server
Docker automatically maps the default PostgreSQL server port 5432 in the container to a host port within the ephemeral port range (typically from 32768 to 61000). This tutorial assumes that port 32768 was used. To check what the actual mapping is, right-click the PostgreSQL container in the Services tool window under the Containers node, click Inspect, and then find the value of the HostPort
field in the Inspection output.
Open the Database tool window ( ).
Click and select
.Set the host name to
localhost
, the port number to32768
(or whatever host port it was mapped to), the default database and user topostgres
. No password is required since we usedtrust
authentication to run the PostgreSQL server.If necessary, download the driver and test the connection.
Click OK to add the PostgreSQL server as a data source.
For more information about working with database sources in GoLand, see Database tools and SQL.