Docker环境下SonarQube容器无法连接PostgreSQL容器求助
Alright, let's sort out this connection problem where your SonarQube container exits right after starting because it can't reach the PostgreSQL container. The java.net.NoRouteToHostException is the key clue here—SonarQube can't establish a network path to your Postgres instance, and here are the most reliable fixes:
1. Use a Docker Custom Network (Recommended Approach)
Docker's default bridge network has limitations for container-to-container communication. Creating a custom network lets containers resolve each other by their names directly, which is way more stable than relying on the host IP.
Step-by-Step Changes:
- Create a custom network first:
docker network create sonar-postgres-network - Update your Postgres start script to attach the container to this network:
Modify thedocker runline to add--network sonar-postgres-network:docker run --name ${container} --network sonar-postgres-network -p 5432:5432 -e POSTGRES_PASSWORD=sonar -d ${image}:latest - Update your SonarQube start script:
- Remove the
--add-host=database:x.x.x.xline (it's no longer needed) - Change the
SONARQUBE_JDBC_URLto use your Postgres container name (test-psql) instead of the host IP:-e SONARQUBE_JDBC_URL=jdbc:postgresql://test-psql:5432/sonar \ - Add the same network flag to the SonarQube
docker runcommand:--network sonar-postgres-network \
- Remove the
This way, SonarQube can directly resolve test-psql to the Postgres container's IP within the custom network, no firewall hoops required.
2. Fix Firewall Issues (If You Prefer Using Host IP)
If you want to stick with using the host IP (x.x.x.x), you need to make sure your host's firewall allows incoming connections from the Docker subnet to port 5432:
- For
ufw(Ubuntu/Debian):sudo ufw allow from 172.17.0.0/16 to any port 5432 - For
firewalld(RHEL/CentOS):sudo firewall-cmd --add-rich-rule='rule family="ipv4" source address="172.17.0.0/16" port port="5432" protocol="tcp" accept' --permanent sudo firewall-cmd --reload
Your pg_hba.conf already allows connections from 127.17.0.0/16 (Docker's default subnet), so that part is correct—you just need to let the traffic through the host firewall.
3. Ensure Postgres is Fully Ready Before Starting SonarQube
SonarQube might be trying to connect before Postgres has finished initializing. Add a wait step to your Sonar start script to check if Postgres is ready:
# Wait for Postgres to be fully initialized container_psql="test-psql" until docker exec ${container_psql} pg_isready -U sonar; do echo "Waiting for PostgreSQL to start..." sleep 2 done
Run this right before the docker run command for SonarQube.
Verify the Connection
To confirm everything works, you can test the connection from within the SonarQube container once it's running:
docker exec -it test-sonar psql -h test-psql -U sonar -d sonar
Enter the password sonar—if you get a Postgres prompt, the connection is successful.
内容的提问来源于stack exchange,提问作者emoleumassi

