Java – Docker WARNING: Published ports are discarded when using host network mode

dockerjavaspring-boot

I have a Springboot app that I have Dockeriszed.

I have it exposed on port 80801, and can access it as expected.

http://<ipaddress>:8081

Problem

The Springboot app in the docker container needs to connect to a postgres database on the same host (not in a container), but it appears like it does not gave access to the host network.

Connection to localhost:5432 refused

Docker cmd:

docker run -t --rm -d -p 8081:8081 --name nexct-approval-service-container nexct-approval-service-image

So I have read in order to connect to the network, you can use:

--network host 

However, then it stops allowing access to the application itself (port 8081):

WARNING: Published ports are discarded when using host network mode

Question

How can I allow access to the SpringBoot app on port 8081 and allow the Springboot app access to the host network so it can connect to the database?

UPDATE

My database connection is defined in Spring Boot:

application.properties

spring.datasource1.driver-class-name=org.postgresql.Driver
spring.datasource1.jdbc-url=jdbc:postgresql://localhost:5432/pims
spring.datasource1.username=postgres
spring.datasource1.password=

MultipleDBConfig.java

@Configuration
@ComponentScan(basePackages = "com.nexct")
public class MultipleDBConfig {

    @Bean(name = "datasource1")
    @ConfigurationProperties("spring.datasource1")
    @Primary
    public DataSource dataSource1(){
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "datasource2")
    @ConfigurationProperties("spring.datasource2")
    public DataSource dataSource2(){
        return DataSourceBuilder.create().build();
    }
}

Best Answer

You can not publish port in the network mode host.

Note: Given that the container does not have its own IP-address when using host mode networking, port-mapping does not take effect, and the -p, --publish, -P, and --publish-all option are ignored, producing a warning instead:

host networking

How can I allow access to the SpringBoot app on port 8081 and allow the Springboot app access to the host network so it can connect to the database?

Still, you can not reach to Host network by assigning host network to the container. To reach host Network you can use Host IP or use special DNS for mac and window.

host.docker.internal:DB_PORT

Or you can use Host IP if you are on linux

HOST_IP:DB_PORT

or you can try (works on ubuntu)

docker run -it --rm -e HOST_IP=$(ip -o route get to 8.8.8.8 | sed -n 's/.*src \([0-9.]\+\).*/\1/p') image_name

Now use HOST_IP as a host name in your application.