简体   繁体   中英

Host to Docker Container to Docker Container communication

I'm building 2 docker containers, "app" and "db", via a docker-compose file.

The app server just installs java/tomcat via a Dockerfile which is what docker-compose uses to build.

The db server uses an MS SQL image.

When I run: docker-compose up

I follow that with a build process of software I need to load which deploys a war to the tomcat directory in the app server and builds the database in the database server.

My problem is: The build process can reference localhost:8080 to install/patch the software to the app server and reference localhost:1433 to install/patch the database portion of the software to the database server. However, when I start Tomcat the system doesn't come online because the app server can't connect to the database server via "localhost:1433" so it requires me to jump in and update the properties file after the build to the docker internal IP address and THEN it works.

My question is: How am I able to get my localhost and my app container to reference the DB in the same manner in a database url?

Dockerfile for app server:

FROM centos:centos7

COPY apache-tomcat-9.0.20.tar.gz /tmp/

WORKDIR /tmp/
RUN yum -y update
RUN yum -y install java-11-openjdk-devel
RUN tar -xf apache-tomcat-9.0.20.tar.gz
RUN mv apache-tomcat-9.0.20 /opt/tomcat/
RUN export JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.212.b04-0.el7_6.x86_64/
RUN export PATH=$PATH:$JAVA_HOME/jre/bin
RUN export CATALINA_HOME=/opt/tomcat/
RUN export PATH=$PATH:$CATALINA_HOME/bin
WORKDIR /opt/tomcat/webapps
RUN mkdir testapp
    enter code here
    enter code here

Docker-Compose File:

version: '3.3'
services:
  db:
    image: "mcr.microsoft.com/mssql/server:2017-latest"
    restart: always
    volumes:
      - db_data:/var/lib/mssql
    environment:
      - ACCEPT_EULA=Y
      - SA_PASSWORD=Test123
    network_mode: bridge
    hostname: db
    ports:
      - "1433:1433"
  app:
    build: './testapp'
    volumes:
      - './system/build:/opt/tomcat/webapps/testapp/'
    ports:
      - "8080:8080"
      - "8009:8009"
    network_mode: bridge
    tty: true
    depends_on:
      - db
volumes:
  db_data:

Bring your service to the same network and target the service by service name. For that you need to define a docker network like below. For the following example I can access DB with http://mongo:27017 .

mongo:
 image: mongo:latest
 ports:
   - "27017:27017"
 volumes:
  - ./data/db:/data/db
 networks:
  - my-net

spring:
 depends_on:
   - mongo
 image: docker-spring-http-alpine
 ports:
   - "8080:8080"
 networks:
   - my-net

networks:
  my-net:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM