Docker image not connecting with a database running on same machine

I have created a docker image of my web application. I have a cassandra database running on my laptop and I am starting the container of my web application from the same laptop. The uri to connect to database is localhost:9042 . However, the image is not able to connect with the database. The connection to database in general works because when I run the application from the IDE then the application starts successfully.

On running docker run --publish 9000:9000 myApp or docker run --network="hosts" myApp, I get error

[trace] CassandraRepositoryComponents - database will connect using parameters uri: cassandra://localhost:9042/, cluster name: myCluster
[trace] s.d.c.CassandraConnectionUri - created logger Logger[services.db.cassandra.CassandraConnectionUri]
[trace] s.d.c.CassandraConnectionManagementService - creating session with uri CassandraConnectionUri(cassandra://localhost:9042/) and cluster name myCluster
[trace] s.d.c.CassandraConnectionManagementService - exception in connecting with database com.datastax.driver.core.exceptions.NoHostAvailableException: All host(s) tried for query failed (tried: localhost/127.0.0.1:9042 (com.datastax.driver.core.exceptions.TransportException: [localhost/127.0.0.1:9042] Cannot connect))
Oops, cannot start the server.

docker file

FROM openjdk:8
RUN mkdir deploy
WORKDIR deploy
COPY target/universal/myapp-1.0.zip .

COPY conf/logback_dev.xml ./logback.xml
COPY conf/application_dev.conf ./application.conf
RUN unzip myapp-1.0.zip
RUN chmod +x myapp-1.0/bin/myapp
EXPOSE 9000
ENTRYPOINT myapp-1.0/bin/myapp -Dplay.http.secret.key=changemeplease -Dlogger.file=/deploy/logback.xml -Dconfig.file=/deploy/application.conf

Cassandra is running as a standalone application and not as a container

Is --network="hosts" a typo?

Either this is a bridge/overlay network, then the published ports make sense, but localhost:9042 can not work. Or this is --network=host and the publised port will be ignored - but then localhost:9042 should work

When a bridged/overlay network is used, localhost inside a container is local to the container, not to the host. You need to use the host ip or hostname to access services from the host.

When host (not hosts!) network is used, localhost inside the container actualy is localhost from the host - network-wise processes in the container behave then like if they run as a local process on the host.

1 Like