简体   繁体   中英

How to specify environment variables in application.properties file so my application can use Docker container MySQL not local MySQL in Spring?

i'm new to Dockers,i want my spring application to access MySQL db from container but i don't know how to add environment variables in docker-compose file and application.properties file so my application can use MySQL db containing in Docker MySQL image.but make sure this is spring application not spring boot

below is the docker-compose file i tried to write

 version: '3'
services:
  mysql-standalone:
    image: 'mysql:5.7'
    environment:
      - MYSQL_ROOT_PASSWORD=root
      - MYSQL_USER=root
      - MYSQL_PASSWORD=root
      - MYSQL_DATABASE=CTH
    ports:
      - "3307:3306"
  cth-docker-container:
    image: cth-docker-container
    ports:
      - "8082:8082"
    environment:
      CTH_MYSQL_DATABASENAME: CTH
      CTH_MYSQL_SERVERNAME: mysql-standalone
      CTH_MYSQL_USERNAME: root
      CTH_MYSQL_PASSWORD: root

      CTH_CHAT_MYSQL_DATABASENAME: CTH_CHAT
      CTH_CHAT_MYSQL_SERVERNAME: mysql-standalone
      CTH_CHAT_MYSQL_USERNAME: root
      CTH_CHAT_MYSQL_PASSWORD: root
    build:
      context: "./"
      dockerfile: "Dockerfile"
    depends_on:
      - mysql-standalone

and application.properties file which has db properties

dbuser.local=root
dbpassword.local=root
dbdatabaseName.local=CTH
dbserverName.local=localhost
dbportNumber.local=3306

i don't know how to create environment variables so my application knows to use use MySQL db present inside MySQL-standalone image

With docker-compose you create a container.

Inside your container there are:

  • database= CTH
  • username = root
  • password = root
  • port = 3307(port expose outside):3306(port expose inside container)

if you want to connect to database from your Spring application you have to change your application.properties like this:

  • spring.datasource.url=jdbc:mysql://localhost:3307/CTH
  • spring.datasource.username=root
  • spring.datasource.password=root
  • spring.datasource.driver-class-name=com.mysql.jdbc.Driver

(you can find properties in this site https://spring.io/guides/gs/accessing-data-mysql/ under "Create the application.properties File" section)

Finally, I found how to create environment variables in the application.properties file which can consume data from the docker-compose file and can able to give values when my application is running locally.

key.name=${value_consuming_from_docke_compose_file:i_can_give_value_when_application_is running_locally}

this is the way but anyone gets another way stuck in a different scenario please find the answer and post here.

Thanks!

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