Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Docker. Spring application. set & get environment variable

I'm trying to dockerize my Spring applicaiton.

Problem: I can't get the environment variable in my Spring app from the docker container.

Spring config (2 options, tried separately)

<bean class="java.net.URI" id="dbUrl">
    <constructor-arg value="#{systemProperties['JDBC_CONNECTION_STRING']}"/>
</bean>

<bean class="java.net.URI" id="dbUrl">
    <constructor-arg value="#{systemEnvironment['JDBC_CONNECTION_STRING']}"/>
</bean>

also tried in java

URI dbUrl = URI.create(System.getProperty("JDBC_CONNECTION_STRING"));

My docker configs. Used docker-compose build and docker-compose up each time updated the values.

docker-compose.yml

app:
  build: .
  command: catalina.sh run
  ports:
    - "8888:8080"
  links:
    - postgres
  volumes:
    - /usr/bin

postgres:
  image: postgres:9.5
  ports:
    - "5432"
  volumes:
  - /var/lib/postgresql/data

Dockerfile

FROM tomcat:jre8

ENV JDBC_CONNECTION_STRING 'postgres://postgres:password111@postgres:5432/mydb'

RUN ["rm", "-fr", "/usr/local/tomcat/webapps/ROOT"]
RUN apt-get update && apt-get install -y net-tools postgresql-client

COPY ./target/myapp.war /usr/local/tomcat/webapps/ROOT.war

CMD ["catalina.sh", "run"]

once i connect to container's bash, set command don't show my variable. But echo $JDBC_CONNECTION_STRING showing the value.

like image 944
user1935987 Avatar asked Sep 08 '16 13:09

user1935987


2 Answers

In java code you are using java system property, but not the system environment variable. In order to pass system property to java process you need to specify -Dkey=value in running command.

So if this is tomcat you can set in $JAVA_OPTS="... -DJDBC_CONNECTION_STRING=$JDBC_CONNECTION_STRING"

like image 151
Vitaliy Zhovtyuk Avatar answered Sep 28 '22 06:09

Vitaliy Zhovtyuk


I think you are confusing between 2 methods: System.getProperties(String) and System.getenv(String). The previous one is used to get the java-specific system environment variables (-D properties), while the later method will get the System environment variables. So in order to use the System environment variables (which configured in docker) you should use method:

URI dbUrl = URI.create(System.getenv("JDBC_CONNECTION_STRING"));
like image 40
Thinhbk Avatar answered Sep 28 '22 08:09

Thinhbk