- 1 year ago
Connect to postgres on docker container via localhost is failed
When attempting to connect to a PostgreSQL database running inside a Docker container using "localhost" as the host, it may fail because the container network is isolated from the host network by default. However, you can use the container's IP address or Docker's port forwarding feature to establish a successful connection. Here's how:
Get the container's IP address:
- Run the following command to retrieve the IP address of your PostgreSQL container:yaml
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' <container_name_or_id>
- Replace
<container_name_or_id>
with the name or ID of your PostgreSQL container.
- Run the following command to retrieve the IP address of your PostgreSQL container:
Connect to PostgreSQL using the container's IP address:
- Use a PostgreSQL client (such as
psql
or a graphical client) and provide the container's IP address, along with the appropriate username, password, and database name, to establish a connection. For example:phppsql -h <container_ip_address> -U <username> -W <database_name>
- Replace
<container_ip_address>
with the IP address obtained in step 1,<username>
with the PostgreSQL username, and<database_name>
with the name of the database you want to connect to.
- Use a PostgreSQL client (such as
Alternatively, you can leverage Docker's port forwarding feature to connect to the PostgreSQL container using "localhost" as the host:
Start the PostgreSQL container with port forwarding:
- When running the PostgreSQL container, use the
-p
flag to forward the PostgreSQL port (default is 5432) from the container to the host. For example:arduinodocker run -d -p 5432:5432 --name my-postgres-container -e POSTGRES_PASSWORD=mysecretpassword postgres
- When running the PostgreSQL container, use the
Connect to PostgreSQL using "localhost" and forwarded port:
- With port forwarding in place, you can connect to the PostgreSQL container using "localhost" as the host and the forwarded port (5432 in this example). For example:php
psql -h localhost -p 5432 -U <username> -W <database_name>
- Replace
<username>
with the PostgreSQL username, and<database_name>
with the name of the database you want to connect to.
- With port forwarding in place, you can connect to the PostgreSQL container using "localhost" as the host and the forwarded port (5432 in this example). For example:
By using the container's IP address or port forwarding, you should be able to connect to the PostgreSQL database running inside the Docker container.