Creating Docker Images
Once you have a clear understanding of Docker and its ecosystem, it's time to dive into the process of creating Docker images. Docker images serve as blueprints for your application, containing everything needed to run it in a containerized environment.
Dockerfile: Building the Blueprint
To create a Docker image, you'll typically start with a Dockerfile. A Dockerfile is a text file that contains instructions for building the image. It specifies a base image, sets up dependencies, copies files, and configures the container environment.
Let's take a look at an example Dockerfile for a Java Spring Boot application:
1# Start with a base image
2FROM openjdk:11
3
4# Set the working directory
5WORKDIR /app
6
7# Copy the application JAR file
8COPY target/myapp.jar ./
9
10# Expose port
11EXPOSE 8080
12
13# Define the command to run the application
14CMD ["java", "-jar", "myapp.jar"]
In this Dockerfile:
- We start with the
openjdk:11
base image, which contains the Java Development Kit (JDK) needed to run Java applications. - We set the working directory to
/app
in the container. - We copy the compiled JAR file of our Java Spring Boot application to the container's
/app
directory. - We expose port
8080
so that the application is accessible from outside the container. - We define the command to run the application, which is
java -jar myapp.jar
.
Building the Docker Image
Once you have the Dockerfile ready, you can build the Docker image using the docker build
command. Open your terminal and navigate to the directory containing the Dockerfile, then run the following command:
1docker build -t myapp-image .
This command tells Docker to build an image based on the Dockerfile located in the current directory (.
) and tag it as myapp-image
.
Running the Docker Image
After successfully building the Docker image, you can run it using the docker run
command. The following command runs the container from the built image and maps port 8080
on the host to port 8080
inside the container:
1docker run -p 8080:8080 myapp-image
Congratulations! You have created a Docker image for your Java Spring Boot application and run it in a containerized environment. In the next lesson, we will explore how to effectively manage and orchestrate Docker containers.
xxxxxxxxxx
class Main {
public static void main(String[] args) {
// replace with your Java logic here
for(int i = 1; i <= 100; i++) {
if(i % 3 == 0 && i % 5 == 0) {
System.out.println("FizzBuzz");
} else if(i % 3 == 0) {
System.out.println("Fizz");
} else if(i % 5 == 0) {
System.out.println("Buzz");
} else {
System.out.println(i);
}
}
}
}