Docker容器内连接localhost 5432端口被拒绝,如何解决?
Hey there, let's break down why you're hitting that connection refused error and get your port 5432 working properly.
The Root Cause
First off, the EXPOSE instruction in your Dockerfile doesn't actually start a service or open the port—it's just metadata that tells Docker (and other users) the container is intended to use that port. Right now, your Ubuntu 14.04 container has no software listening on port 5432, so when you run nc to connect, there's nothing there to accept the request.
Since 5432 is the default port for PostgreSQL, I'll walk you through setting up that service to listen on the port, but the same logic applies for any service you want to run on this port.
Step 1: Update Your Dockerfile to Install PostgreSQL
Modify your Dockerfile to install PostgreSQL and ensure it runs when the container starts:
FROM ubuntu:14.04 # Update apt sources and install PostgreSQL 9.3 (the version available in Ubuntu 14.04 repos) RUN apt-get update && apt-get install -y postgresql-9.3 # Keep the EXPOSE instruction to document the port EXPOSE 5432 # Start PostgreSQL and keep the container running (tail the log to stay in foreground) CMD ["bash", "-c", "service postgresql start && tail -f /var/log/postgresql/postgresql-9.3-main.log"]
The tail -f command is crucial here—Docker containers exit when their foreground process stops. Starting PostgreSQL with service runs it in the background, so we need a foreground process to keep the container alive.
Step 2: Rebuild and Run the Container
First, rebuild your image:
docker build -t expose_5432_port .
Then run the container in detached mode, then exec into it to test:
docker run -d expose_5432_port # Find your container ID or name docker ps # Exec into the container docker exec -ti <container_id_or_name> /bin/bash
Step 3: Verify the Connection
Once inside the container, first confirm PostgreSQL is running:
service postgresql status
You should see output indicating it's active. Now run your nc command again:
nc -v -z 127.0.0.1 5432
This time, it should succeed with something like:
Connection to 127.0.0.1 5432 port [tcp/postgresql] succeeded!
Quick Test Alternative (No PostgreSQL)
If you just want to test port connectivity without installing PostgreSQL, you can manually start a listener in the container:
- Run your original container:
docker run -ti expose_5432_port /bin/bash - In the container, start a background netcat listener:
nc -l 5432 & - Now run your test
nccommand:nc -v -z 127.0.0.1 5432
You'll see the connection succeed because there's now a process listening on the port.
内容的提问来源于stack exchange,提问作者en803

