When deploying applications with Docker, it's common to run the database inside another container using Docker Compose. However, there are scenarios where your PostgreSQL database runs on the host machine while your web server runs inside a container. In this post, we'll explore how to configure Docker’s host networking mode to enable communication between the two.
By default, Docker assigns a separate network namespace to each container, meaning containers communicate via virtual networks. But with host networking (--network host
), the container shares the host machine’s network stack, allowing it to access services running on localhost
directly.
Step 1: Run the Web Server Container
To run your web server inside a container and allow it to connect to PostgreSQL running on the host, use the following command (here I am using this image → awsclouddev/sre-bootcamp-web-server:v4.0)
docker run -itd --name ws-1 -p 3000:3000 --network host --env-file=<path-for-env-file> awsclouddev/sre-bootcamp-web-server:v4.0
--network="host"
: Enables the host network mode.-d
: Runs the container in detached mode.
Step 2: Configure the Web Server to Use Host Database
Since the container now shares the host’s network, use localhost
or 127.0.0.1
as the database host in your application.
If you're using environment variables, modify your connection settings like this:
DATABASE_HOST=localhost
DATABASE_PORT=5432
DATABASE_USER=<DB_USERNAME>
DATABASE_PASSWORD=<DB_PASSWORD>
DATABASE_NAME=<DB_NAME>
Alternatively, if your web server uses a configuration file (e.g., config.yaml
or .env
), ensure it points to localhost
instead of a Docker network alias.
Switch to your browser and check the health status of the api at http://localhost:3000/v1/healthcheck
Run the following curl
command and check this route http://locahost:3000/v1/students
curl -X POST http://localhost:3000/v1/students \
-H "Content-Type: application/json" \
-d '{"name": "Alice", "age": 23, "department": "MECH"}'
When to Avoid Host Networking?
While host networking is simple, it’s not always ideal:
✅ Use it when:
You need low-latency communication with host services.
You’re running the application locally and don’t want to expose additional ports.
You want to avoid configuring Docker networks.
❌ Avoid it when:
You need container isolation for security reasons.
The application must run on different network interfaces (e.g., multiple containers communicating internally).
You plan to deploy in production environments where network conflicts may arise.
Using Docker’s host network mode is a powerful way to connect a containerized web server to a PostgreSQL database running on the host without exposing ports or modifying firewall rules. This method simplifies local development and testing but should be used carefully in production due to security considerations.