Junior — Middle
How do you create a Docker container for a Java application by describing it in a Dockerfile?
sobes.tech AI
Answer from AI
To create a Docker container for a Java application, you typically write a Dockerfile that describes the steps to build the image. Here's an example of a simple Dockerfile for a Java application:
# Use the official image with JDK
FROM openjdk:17-jdk-slim
# Set the working directory inside the container
WORKDIR /app
# Copy the compiled jar file into the container
COPY target/myapp.jar ./
# Specify the command to run the application
CMD ["java", "-jar", "myapp.jar"]
Explanation:
FROM— base image with JDK installed.WORKDIR— directory inside the container where commands will be executed.COPY— copies the jar file from the localtargetfolder into the container.CMD— command that runs the Java application.
To build the image, use:
docker build -t my-java-app .
And to run the container:
docker run -it --rm my-java-app