Externalising Spring Boot properties when deploying to Docker

前端 未结 6 1952
天命终不由人
天命终不由人 2020-12-01 04:20

In my Spring Boot app I want to externalise the properties to run in a Docker container. When first deployed, the properties that are currently in my-server/src/main/

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-01 05:08

    DOCKER IMAGE CONFIGURATION

    If you look to the way Spring recommends to launch a Spring Boot powered docker container, that's what you find:

    FROM openjdk:8-jdk-alpine
    VOLUME /tmp
    ARG JAR_FILE
    COPY ${JAR_FILE} app.jar
    ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/app.jar"]
    

    That means your image extends openjdk and your container has its own environment. If you're doing like that, it would be enough to declare what you want to override as environment properties and Spring Boot will fetch them, since environment variables take precedence over the yml files.

    Environment variables can be passed in your docker command too, to launch the container with your desired configuration. If you want to set some limit for the JVM memory, see the link below.


    DOCKER COMPOSE SAMPLE

    Here you have an example of how I launch a simple app environment with docker compose. As you see, I declare the spring.datasource.url property here as an environment variable, so it overrides whatever you've got in your application.yml file.

    version: '2'
    services:
        myapp:
            image: mycompany/myapp:1.0.0
            container_name: myapp
            depends_on:
            - mysql
            environment:
                - SPRING_DATASOURCE_URL=jdbc:mysql://mysql:3306/myapp?useUnicode=true&characterEncoding=utf8&useSSL=false
            ports:
                - 8080:8080
    
        mysql:
            image: mysql:5.7.19
            container_name: mysql
            volumes:
                - /home/docker/volumes/myapp/mysql/:/var/lib/mysql/
            environment:
                - MYSQL_USER=root
                - MYSQL_ALLOW_EMPTY_PASSWORD=yes
                - MYSQL_DATABASE=myapp
            command: mysqld --lower_case_table_names=1 --skip-ssl --character_set_server=utf8
    

    See also:

    • How do I pass environment variables to Docker containers?
    • Limit JVM memory consumption in a Docker container

提交回复
热议问题