docker-compose java application connection to mongodb

前端 未结 2 530
醉梦人生
醉梦人生 2021-01-28 02:35

2 Containers, one Java application and the second mongodb.

If I run my java app locally and mongodb in a container, it connects but if both run inside a container, java

2条回答
  •  伪装坚强ぢ
    2021-01-28 03:34

    At 2019 July, official docker documentation :

    Source: https://docs.docker.com/compose/compose-file/#links

    Possible solution

    Centralize all configurations in a file with environment variables and execute it before docker-compose up

    The following approach helped me in this scenarios:

    • If you need to run several docker-compose.yml files with dependencies between them
    • Some of your services in your docker-compose needs to connect to another process in the same machine. This process could be a docker container or not.
    • You need to share variables between several docker-compose files like host, passwords, etc

    Steps

    Create one file to centralize configurations

    This file could be named: /env/company_environments with extension or not.

    export MACHINE_HOST=$(hostname -I | awk '{print $1}')
    export GLOBAL_LOG_PATH=/my/org/log
    export MONGO_PASSWORD=mypass
    export ANOTHER_GLOBAL_VARIABLE=123456
    

    docker-compose A

    app1:
      environment:
        - MONGO_HOST=$MACHINE_HOST
        - MY_TOKEN=$ANOTHER_GLOBAL_VARIABLE
    

    docker-compose B

    app2:
      environment:
        - LOG_PATH=$GLOBAL_LOG_PATH
        - MONGO_PASSWORD=$MONGO_PASSWORD
        - NOT_DOCKER_POSTGRESS_JDBC_URL_IN_SAME_MACHINE=jdbc:postgresql://$MACHINE_HOST/database
    

    Startup your apps

    Just add source before docker-compose commands:

    source /env/company_environments
    docker-compose up -d
    

    If you have another docker-compose.yml file , you just need to execute the same commands in the folder of your another docker-compose.yml:

    source /env/company_environments
    docker-compose up -d
    

提交回复
热议问题