Docker commit for docker image construction

Time:2022-6-19

We can pull images from public warehouses, but sometimes the images pulled from public warehouses do not meet our needs. Although it has been freed from the tedious deployment work, during actual development, we may want to mirror the complete environment of the entire project, pull and package the complete image on other machines, and run it directly.

​ Docker supports self built images and uploading self built images to public warehouses. Image building can be realized in the following two ways:

  • docker commit: create a new image from the container;
  • docker huild: create an image with dockerfile file;

Example: bydocker commitTo realize the construction of the image through the basic imagecentos:7, install JDK and Tomcat in the image to create a new image.

1. Create container

#Pull image
docker pull centos:7

#Create container
docker run -id --name centos7 centos:7

2. Copy resources

Copy the JDK and Tomcat of the host to the container

docker cp jdk-11.0.7_linux-x64_bin.tar.gz centos7:/root
docker cp apache-tomcat-9.0.39.tar.gz centos7:/root

3. Install resources

#Enter container
docker exec -it centos7 /bin/bash

Do the following in the container:

#Switch to /root directory
cd root/

#Create Java and Tomcat directories
mkdir -p /usr/local/java
mkdir -p /usr/local/tomcat

#Extract JDK and Tomcat into the Java and Tomcat directories of the container
tar -zxvf jdk-11.0.6_linux-x64_bin.tar.gz -C /usr/local/Java/
tar -zxvf apache-tomcat-9.0.39.tar.gz -C /usr/local/tomcat/

#Add the following to the environment variables file
export JAVA_HOME=/usr/local/java/jdk-11.0.6/
export PATH=$PATH:$JAVA_HOME/bin

#Reload environment variables file
source /etc/profile

#Test whether the environment variables are configured successfully
[[email protected] etc]# java -version
java version "11.0.7" 2020-04-14 LTS
Java(TM) SE Runtime Environment 18.9 (build 11.0.7+8-LTS)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.7+8-LTS, mixed mode)

4. Build image

docker commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]

docker commit -a="xiaoyang" -m="jdk11 and tomcat" centos7 mycentos:7
  • -a: submitted image author;
  • -c: use the dockerfile instruction to create an image;
  • -m: descriptive text at the time of submission;
  • -p: pause the container during commit;

image-20220331163547657

5. Create container with built image

#Create container
docker run -id --name mycentos7 -p 8080:8080 mycentos:7

#Enter container
docker exec -it mycentos7 /bin/bash

#Reload profile
source /etc/profile

#Test Java environment variables
[[email protected] /]# java -version
java version "11.0.7" 2020-04-14 LTS
Java(TM) SE Runtime Environment 18.9 (build 11.0.7+8-LTS)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.7+8-LTS, mixed mode)

#Start Tomcat
/usr//local/tomcat/apache-tomcat-9.0.39/bin/startup.sh