Home  >  Q&A  >  body text

How to share database schema in DockerCompose files?

I am learning Docker. I'm building an image from a Dockerfile in a counter application. And I use mysql as database. The DockerCompose file uses one database and two containers from the same application image. Mysql database has two different modes. My goal is to have separate application services with different ports (e.g. 9000 and 9001) and they have their own schema. When I call localhost:9000/index it shows the first counter and when I call localhost:9000/index it shows the second counter.

But the problem is that they both use the first pattern, so the result is the same counter. How to isolate architecture?

Write file->

version: '3.1'

services:

  mysql:
    image: mysql
    restart: always
    ports:
      - "3306:3306"
    environment:
      MYSQL_ROOT_PASSWORD: password
    volumes:
      - mysql_data:/var/lib/mysql


  hello-docker:
    image: hello-docker:0.0.2
    restart: always
    environment:
      DB_CONNECTION_IP: mysql
      DB_SCHEMA_NAME: hello-counter
    ports:
        - "9000:9000"
    volumes:
        - mysql_data:/var/lib/mysql

  hello-docker2:
    image: hello-docker:0.0.2
    restart: always
    environment:
      DB_CONNECTION_IP: mysql
      DB_SCHEMA_NAME: hello_counter2
    ports:
      - "9001:9000"

volumes:
  mysql_data:

application.yaml->

spring:
  datasource:
    url: &connectionUrl jdbc:mysql://${DB_CONNECTION_IP:localhost}:${DB_CONNECTION_PORT:3306}/${DB_SCHEMA_NAME}?allowPublicKeyRetrieval=true&createDatabaseIfNotExist=true&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone= UTC&zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=UTF-8
    username: root
    password: password
    driver-class-name: com.mysql.cj.jdbc.Driver
  jpa:
    hibernate.ddl-auto: validate
    generate-ddl: true
    show-sql: true
    properties.hibernate.format_sql: true


server:
  port: 9000

P粉032977207P粉032977207213 days ago253

reply all(1)I'll reply

  • P粉475315142

    P粉4753151422024-03-20 14:54:05

    It is best to have a separate docker compose for each application and its database.

    If you only want to use one docker compose for two applications, you can define two separate services for mysql with different exposed schemas and ports, and reference each of them in the application.

    This is the same application for which you have two services defined.

    also:

    You mentioned the same application, you seem to mean:

    localhost:9000/index

    and

    localhost:9001/index

    reply
    0
  • Cancelreply