Custom Docker Image
Image is a file package including applications, system function libraries for applications and configurations. Creating a custom image is the process of making a package like this.
Layer
To make a java application image, we may need to include
- Ubuntu base image
- JRE env variables
- Jar package
- A script for launching (e.g.
java -jar xx.jar
) And finally get a Java application.
Each of the above items forms a layer. All layers forms the image.
An advantage of seperating an image into layers is that the layers can be shared among different images.
Two common layers are:
- BaseImage (system functions, env, conf, etc. The layer at the bottom)
- EntryPoint (usually the script and parameters to start the applications. The layer at the top)
A good news: we don't need to construct all layers by ourselves. We can use dockerfile to tell docker the structure of our image. Docker will make the image for us.
Dockerfile
Common Docker Instructions
A dockerfile contains many docker instructions. Here are some common ones.
Instruction | Desc | e.g. |
---|---|---|
FROM | choose the base image | FROM centos:6 |
ENV | set env variables, such as time zone | ENV key value |
COPY | copy local file to a directory of the image | COPY ./jrell.tar.gz /tmp |
RUN | execute linux shell commands | RUN ls |
EXPOSE | specify the port that will be listened. This is a clarification for the user of the container, who still need to use -p to configure ports. | EXPOSE 8080 |
ENTRYPOINT | the command to be called when the container starts | ENTRYPOINT java -jar xx.jar |
An Example
First, this version does everything from scratch:
FROM ubuntu:16.04
ENV JAVA_DIR=/usr/local
COPY ./jdk8.tar.gz $JAVA_DIR/
COPY ./docker-demo.jar /tmp/app.jar
RUN cd $JAVA_DIR \ && tar -xf ./jdk8.tar.gz \ && mv ./jdk1.8.0_144 ./java8
ENV JAVA_HOME=$JAVA_DIR/java8
ENV PATH=$PATH:$JAVA_HOME/bin
ENTRYPOINT ["java", "-jar", "/app.jar"]
This version is simpler, based on JDK image:
FROM openjdk:11.0-jre-buster
COPY docker-demo.jar /app.jar
ENTRYPOINT ["java", "-jar", "/app.jar"]
Building the Image
Once we have a dockerfile, we can build an image using a command.
docker build -t myImage:1.0 .
-t
gives the image a name,:1.0
means version (default: latest).
specifies the directory that dockerfile is in
Then you can check the built image using docker images
.