I'm new to Spring and Docker.
I created a project by using the default template provided by Gitlab.
It comes with a predefined Dockerfile on which I would like to add some extra environment variables to be used inside my application.properties
.
What I've done so far is adding the MY_PROP
ENV value inside the DockerFile like this:
FROM maven:3-jdk-8-alpine
WORKDIR /usr/src/app
COPY . /usr/src/app
RUN mvn package
ENV PORT 5000
ENV MY_PROP testpropertyfromdocker
EXPOSE $PORT
CMD [ "sh", "-c", "mvn -Dserver.port=${PORT} spring-boot:run" ]
Set my application.properties
like this:
test.prop=${MY_PROP}
And try to use it in a basic RestControntroller
:
@SpringBootApplication
@RestController
public class DemoApplication {
@Value("${test.prop}")
private String testProp;
@GetMapping("/")
String home() {
return "My prop from docker: " + testProp;
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
But if I try to build my Docker image with
docker build -t demo .
It fails on
java.lang.IllegalArgumentException: Could not resolve placeholder 'MY_PROP' in value "${MY_PROP}"
I've also tried to run the project directly in IntelliJ without building the Docker image but got the same error even when adding a .env
file.
How do I pass my environment variable to my Spring application ?
Is it possible to have a .env
file or similar to use when debugging inside the IDE or do I have to build the image to be able to run the project ?
PS: I don't think this is a duplicate of Externalising Spring Boot properties when deploying to Docker or at least the answer should be more complete as I didn't manage to have my configuration working as expected.
EDIT
I updated my pom.xml
to include this:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.2.2.RELEASE</version>
<configuration>
<environmentVariables>
<MY_PROP>testfromappprops</MY_PROP>
</environmentVariables>
</configuration>
</plugin>
</plugins>
</build>
I made a clean and build and resync maven project but it is still failing even when running through the IDE.
EDIT 2 I update dmy DockerFile to use java -jar:
FROM openjdk:8-jdk-alpine
VOLUME /tmp
ARG JAR_FILE
COPY ${JAR_FILE} app.jar
ENV MY_PROP testpropertyfromdocker
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/app.jar"]
The docker build -t demo .
command line is working but the docker run demo
is giving the following output:
Error: Invalid or corrupt jarfile /app.jar
Also, when running from the IDE (the "run" button), I still have same error about environment variable not found.
Thanks.