How Do I Create a Container Image?

The following two approaches are for you to consider. Approach 1 is for images that will only be updated occasionally whereas approach 2 is for images that will be frequently updated.

Approach 1: Creating a Snapshot

This approach is suitable for images that will only be updated occasionally.

Procedure:

  1. Install the container engine software on a host.
  2. Start an empty base container in the interactive mode.

    For example, start a CentOS container in the interactive mode.

    docker run -it centos

  3. Run the following commands to install the target software:

    yum install XXX

    git clone https://github.com/lh3/bwa.git

    cd bwa;make

    Install Git in advance and check whether an SSH key is set on the local host.

  4. Run the exit command to exit the container.
  1. Create a snapshot.
    docker commit -m "xx" -a "test" container-id test/image:tag
    • -a: indicates the author of the base image.
    • container-id: indicates the ID of the container you have started in step 2. You can run the docker ps -a command to query the container ID.
    • -m: indicates the commit message.
    • test/image:tag: indicates the repository name/image name:tag name.
  1. Run the docker images command to list the built container image.

Approach 2: Creating a Dockerfile to Build an Image

This approach is suitable for images that will be frequently updated. In Approach 1, you create a snapshot of the whole container. This could be demanding if you need to frequently update your images. In this case, Approach 2 is put forward to automate the image build process.

The idea behind Approach 2 is to write the process of Approach 1 into a Dockerfile and then run the docker build -t test/image:tag. command to automatically build an image from the Dockerfile. In the preceding command, . indicates the path to the Dockerfile.

Example Dockerfile:

If an external network is required, ensure that network connectivity is available.

#Version 1.0.1
FROM centos:latest

# Setting the root user as the executor of subsequent commands
USER root

# Performing operations
RUN yum update -y
RUN yum install -y java

# Using && to concatenate commands
RUN touch test.txt && echo "abc" >>abc.txt

# Setting an externally exposed port
EXPOSE 80 8080 1038

# Adding a network file
ADD https://www.baidu.com/img/bd_logo1.png /opt/

# Setting an environment variable
ENV WEBAPP_PORT=9090

# Setting a work directory
WORKDIR /opt/

# Setting a start command
ENTRYPOINT ["ls"]

# Setting start parameters
CMD ["-a", "-l"]

# Setting a volume
VOLUME ["/data", "/var/www"]

# Setting the trigger operation for a sub-image
ONBUILD ADD . /app/src
ONBUILD RUN echo "on build excuted" >> onbuild.txt

Basic Syntax of Dockerfile