I have installed MariaDB on Ubuntu (not as a Docker image). Then I have an image with a Spring Boot Application. This Spring Boot application should be reachable on port 8002 and be able to connect to MariaDB on the host system.
If I start docker run without --network=host, the Spring Boot application in the docker image cannot connect to the database.
If I use the --network=host parameter, the Spring Boot application can connect to the database, but the application is not reachable on port 8002.
docker run \
-e "DB_URL=jdbc:mariadb://127.0.0.1:3306/app" \
-e "DB_USERNAME=***" \
-e "DB_PASSWORD=***" \
-it \
-p 8002:8080 \
--network=host \
repository/app:0.0.3
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
2fe96a608298 repository/app:0.0.3 "java -jar app…" 2 minutes ago Up 2 minutes hardcore_hopper
I have tried many. But I can’t get the application to be reachable on a port.
>Solution :
When you use host networking you are telling docker that you use the host’s networking stack therefore you cannot expose ports on your container. Your application should be running as if it was directly running on your host, meaning you should be able to reach it at port 8080.
To quote the documentation on the host network driver:
If you use the host network mode for a container, that container’s network stack is not isolated from the Docker host (the container shares the host’s networking namespace), and the container does not get its own IP-address allocated. For instance, if you run a container which binds to port 80 and you use host networking, the container’s application is available on port 80 on the host’s IP address.
I am assuming you are on a Linux operating system, since host networking does not work on Windows machines.
The host networking driver only works on Linux hosts, and is not supported on Docker Desktop for Mac, Docker Desktop for Windows, or Docker EE for Windows Server.