To allow an application running in a local container to connect to a PostgreSQL database on the local machine, use the following steps:
-
Make sure the PostgreSQL database is installed and running on this machine. You can use the psql command line tool or other visual tools to manage and connect to databases on your local machine.
-
In the application's configuration file, configure the database connection to connect to a PostgreSQL database on your local machine. Typically, you need to specify the following connection parameters:
- Hostname: usually
localhost
or127.0.0.1
, indicating the local machine. - Port number: By default, PostgreSQL uses port 5432.
- Database name: The name of the database you want to connect to.
- Username and Password: The username and password used to connect to the database.
For example, the database connection configuration in the application configuration file looks like this:
spring.datasource.url=jdbc:postgresql://localhost:5432/mydatabase spring.datasource.username=myuser spring.datasource.password=mypassword
Please make sure to replace in the above configuration
mydatabase
with the actual database name you want to connect to,myuser
andmypassword
with your actual database username and password. - Hostname: usually
-
In the Docker container running locally, ensure that the application can access the PostgreSQL database on the local machine. By default, Docker containers share the network with the local machine and can access services on the local machine through
localhost
or .127.0.0.1
Therefore, you can use the same database connection configuration in the container as natively.If port mapping is used in the container (for example, mapping the container's 8080 port to the local machine's 8080 port), you need to change the host name in the database connection configuration to the local machine's IP address. You can use
docker.for.mac.host.internal
ordocker.for.win.localhost
as hostname, these are special hostnames provided by Docker Desktop on Mac and Windows for accessing services natively.For example, if port mapping is used in the container and the container's 8080 port is mapped to the local machine's 8080 port, the database connection configuration in the application configuration file looks like this:
spring.datasource.url=jdbc:postgresql://docker.for.mac.host.internal:5432/mydatabase spring.datasource.username=myuser spring.datasource.password=mypassword
Please make sure to replace in the above configuration
mydatabase
with the actual database name you want to connect to,myuser
andmypassword
with your actual database username and password.
With the above steps, your application in the local container should be able to connect to the PostgreSQL database on your local machine. Make sure the database connection is configured correctly and the PostgreSQL database on the local machine is running.