Home > Mobile >  Docker compose not passing variables to container in service
Docker compose not passing variables to container in service

Time:11-15

This is my docker-compose file

  services:
  api:
    build:
      context: ./backend
      dockerfile: Dockerfile  
    container_name: api
    ports:
      - 8080:8080
    environment:
      - MYSQL_DB_USER=user
      - MYSQL_DB_PASS=password
      - MYSQL_DB_HOST="jdbc:mysql://dbhost:3306/dbname?autoReconnect=true&serverTimezone=UTC&useSSL=false"
    ...

This is what I get when I try to run docker-compose up

Factory method 'dataSource' threw exception; nested exception is java.lang.IllegalArgumentException: URL must start with 'jdbc'

Everything works fine if I manually run the container passing the envs

docker run --network backend -e MYSQL_DB_USER="user" -e MYSQL_DB_PASS="pass" -e MYSQL_DB_HOST="jdbc:mysql://dbhost:3306/dbname?autoReconnect=true&serverTimezone=UTC&useSSL=false" -it api:1.0

The dockerfile for the API service is multi-staging and is using ENTRYPOINT.

CodePudding user response:

You need to remove the double quotes around the environment value

environment:
  - MYSQL_DB_HOST=jdbc:mysql://dbhost:3306/dbname?autoReconnect=true&serverTimezone=UTC&useSSL=false

From the error message, you can see that the JDBC layer expects something to have removed the quotes before you run the application. And indeed if you were running this in a shell

export MYSQL_DB_HOST="jdbc:...?autoReconnect=true&..."

the shell would remove the double quotes, and they're important there because the ? and & are both "special" characters in shell syntax.

YAML has fewer "special" characters and you often don't need to quote strings (depending on syntax). It's also the case that the shell will handle quoted substrings of a command, but within a single YAML value, either the whole value needs to be quoted or none of it.

Compose supports two different forms of environment:. It can either be a list of KEY=value single YAML strings, or a YAML mapping KEY: value. In the dictionary form it would be acceptable to quote the values (but probably not necessary here).

So also correct:

environment:
  # quote the _whole_ string, but not just part of it
  # (only necessary if your string closely resembles other YAML syntax)
  - "MYSQL_DB_HOST=jdbc:..."
environment:
  # as a mapping, quoting nothing
  # (all environment variables must use this syntax)
  MYSQL_DB_HOST: jdbc:...
environment:
  # as a mapping, quoting the value
  MYSQL_DB_HOST: "jdbc:..."
  • Related