“This is the 19th day of my participation in the First Challenge 2022, for more details: First Challenge 2022”.

background

Docker image construction is successful, as long as there is a Docker environment can be used, but must be pushed to the Docker Hub image. The image created should comply with Docker Hub tag requirements, because the user name registered in Docker Hub is Liboware, and finally use Docker push command to push the image to the public repository.

If the profile

You need to register as a Docker Hub user at hub.docker.com/

For example: Register account name: liboware

Log in to docker from local server:

For example on CentOS7 servers

[root@localhost ~]#  docker login
Login with your Docker ID to push and pull images from Docker Hub. If you donDon't have a Docker ID, head over to https://hub.docker.com to create one. Username: liboware ## ## Enter password WARNING! Your password will be stored unencrypted in /root/.docker/config.json. Configure a credential helper to remove this warning. See https://docs.docker.com/engine/reference/commandline/login/#credentials-store Login SucceededCopy the code

Look at mirror

[root@localhost ~]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
nacos               v1         9e5f6711d527        3 days ago          178MB
mysql               v1                  9e5f6711d527        3 days ago          178MB
Copy the code

Docker tag builds the image

[root@localhost ~]# docker tag nacos:v1 liboware/nacos:v1
Copy the code

Docker Images view images

[root@localhost ~]# docker images 
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
nacos               v1         9e5f6711d527        3 days ago          178MB
nginx               v1                  9e5f6711d527        3 days ago          178MB
liboware/mysql     v1                  9e5f6711d527        3 days ago          178MB
[root@localhost ~]# 
Copy the code

Docker Hub push image

Docker push register docker username /REPOSITORY:TAG

[root@localhost ~]# docker push liboware/nacos:v1
The push refers to repository [docker.io/llxxyy/nginx-io]
833a0f6a6ff9: Pushed 
10bfe402500e: Pushed 
d43641d7d594: Mounted from library/nginx 
c2adabaecedb: Mounted from library/nginx 
v1: digest: sha256:67dcdae5578c0374019cc899731543cfd7c48fe5780e84233a258f2bf7d2ceda size: 1155
[root@localhost ~]# 
Copy the code

Note: Push Docker Hub is slow, wait patiently, and it is likely to fail. If it fails, retransmission will be tried for several times, and then push will be disconnected (but the pushed Docker Hub will be retained for an unknown length of time).

The hub docker effect

Docker uses published images

docker@default:~$ docker search liboware/nacos
NAME                               DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED  
liboware/nacos   In this  image server you can use ma...   0 
Copy the code

In the pull down

[root@localhost ~]# docker pull liboware/nacos:v1
v1: Pulling from liboware/nacos
Digest: sha256:67dcdae5578c0374019cc899731543cfd7c48fe5780e84233a258f2bf7d2ceda
Status: Downloaded newer image for liboware/nacos:v1
docker.io/liboware/nacos:v2
Copy the code

Confirming the pull success

[root@localhost ~]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
nginx               stable-perl         9e5f6711d527        3 days ago          178MB
nginx               v1                  9e5f6711d527        3 days ago          178MB
libo/nacos     v1                  9e5f6711d527        3 days ago          178MB
Copy the code

Problems encountered

  1. * Requested access to the resource is denied * Docker push nacos:v1

  2. We can list all the images: Docker Images

  3. Create a tag image to be published and change it to your account name, my account name: liboware

docker tag nacos:v2  liboware/nacos:v2
Copy the code
  1. Docker push Liboware/nacOS :v2

Use Maven plugin to build Docker image method

This article introduces the use of Maven plugin to build Docker image method, share with you, specific as follows:

tool

To do a good job, he must sharpen his tools. After the author’s investigation, the following Maven plug-ins of Docker came into the author’s view.

Plug-in name + official address

  • docker-maven-plugin Github.com/spotify/doc…

  • Docker — maven plugin github.com/fabric8io/d…

  • Docker — maven plugin github.com/bibryam/doc…

Modify host configuration (Docker can be accessed remotely)

  • Modify the host docker configuration to support remote access.
vi /usr/lib/systemd/system/docker.service
Copy the code

Enable the Docker remote API and modify the Docker configuration file. After the docker.

ExecStart = after adding configuration – H TCP: / / 0.0.0.0:2375 – H Unix: / / / var/run/docker. The sock

Save and exit, reload the configuration file #systemctl daemon-reload, start docker #systemctl start docker.

  • Refresh the configuration and restart the service
systemctl daemon-reload
systemctl restart docker
Copy the code

Configuration DOCKER_HOST

By default, docker-maven-plugin is connected to the local docker address: localhost:2375, so we need to set the environment variable first.

DOCKER_HOST=tcp://<host>:2375
Copy the code

DOCKER_HOST= TCP ://:2375

For example,

  • ExecStart = / usr/bin/dockerd -h TCP: / / 0.0.0.0:2375 – H Unix: / / / var/run/docker. The sock, here to write 4 0, you don’t change your IP oh,

  • Input # netstat anp | grep display docker 2375 is listening on port 2375, enter # curl 127.0.0.1:2375 / info shows a lot of information, to prove the remote API is done

  • Create a new DOCKER_HOST in the Windows environment variable with the value TCP ://10.100.74.220:2375 (you can change your own DOCker server IP address).

Build Docker images using plug-ins

In the process of continuous integration, project engineering generally uses Maven to compile and package, and then generate an image. Through the online image, it can greatly provide the online efficiency, and at the same time can fast dynamic expansion, fast rollback, which is really convenient. The Docker-Maven-plugin is designed to help us automatically generate images and push them to the repository through simple configuration in Maven project.

Add the plug-in

Add the following paragraph to pom.xml:

 <build>Add related mirror plug-ins</build>
Copy the code

Build the mirror

An image can be built either by specifying the build information to the POM or by using an existing Dockerfile. (FROM, ENTRYPOINT, CMD, MAINTAINER, and ADD information can be configured in POM. Dockerfile is not required.)

  • In the first method, FROM, ENTRYPOINT, CMD, MAINTAINER, and ADD information can be configured in the POM without using a Dockerfile

  • Second, if you use VOLUME or other Dockerfile commands, you need to create a Dockerfile and configure a dockerDirectory in the POM to specify the path. (Create a Dockerfile and configure a dockerDirectory in the POM to specify the path)

Add the docker – maven – the plugin
<plugin>
  <groupId>com.spotify</groupId>
  <artifactId>docker-maven-plugin</artifactId>
  <version>0.4.13</version>
  <configuration>
	 <dockerDirectory>${project.basedir}/src/main/docker</dockerDirectory>  
    <imageName>{dockerhub name/imageName}</imageName> 
	 <imageTags>
         <imageTag>{imageTag}</imageTag>
     </imageTags>
    <baseImage>{baseImage}</baseImage>
    <entryPoint>{end[point]}</entryPoint>
	<maintainer>author [email protected]</maintainer>
     <workdir>/ROOT</workdir>
    <resources>
      <resource>
        <targetPath>/</targetPath> 
        <directory>${project.build.directory}</directory>
        <include>${project.build.finalName}.jar</include> 
      </resource>
    </resources>
  </configuration>
</plugin>
Copy the code
  • Dockerhub name /imageName} :

    • Dockerhub name: specifies the name of the dockerHub user. If the name matches the regular [A-z0-9-_.] parameter, the build will fail

    • ImageName: the DockerHub repository name must match the regular [A-z0-9-_.], otherwise the build will not succeed

    • GroupId /{project.groupid}/ project.groupid /{project.artifactid}

  • {imageTag} : indicates the image label, which is the latest tag or version.

  • {baseImage} : specifies the baseImage, which is equivalent to the FROM directive, such as Java, but can be generated directly in dockerfile.

  • {endpoint} : // Equivalent to ENTRYPOINT directives, e.g. [” Java “,”-jar”,”app.jar”]

Copy jar package to docker container specified directory configuration, can also write to Dockerfile

  • {project.build.directory} : Specifies the root directory to copy. ${project.build.directory} represents the target directory.

  • {project.build.finalName} : Specifies the file to be copied. ${project.build.finalname}. Jar refers to the packaged JAR file.

  • Resources. The resource. TargetPath: copies after packaging resource file to the directory;

  • Resources. The resource. Directory: need to copy the file directory, maven packaged application jar packages exist below the target directory;

  • Resources. The resource. Include: the need to copy the file, packaged good application jar package.

Reading Dockerfile files does not require baseImage and EntryPoint to be specified

  • Specify the Dockerfile file to read:
<dockerDirectory>${project.basedir}/src/main/docker</dockerDirectory>
Copy the code

Create Dockerfile

\src\main\docker

The following
FROM Java :8 VOLUME/TMP ADD admin-service-80-0.0.1 -snapshot. jar admin-service-80.jar RUN bash -c 'touch /admin-service-80.jar' EXPOSE 80 ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","${project.build.finalName}.jar"]Copy the code
Run the following command to build the Docker image

mvn clean package docker:build

[INFO] -- Building image mavenDemo Step 1/5 :1.0.0:build (default-cli) @mavendemo -- [INFO] Building image mavenDemo Step 1/5: FROM java ---> d23bdf5b1b1b Step 2/5 : MAINTAINER docker_maven [email protected] ---> Using cache ---> 2faf180d4a50 Step 3/5 : WORKDIR /ROOT ---> Using cache ---> 862210f7956a Step 4/5 : ENTRYPOINT java -jar mavenDemo.jar ---> Running in 96bbe83de6ec ---> c29009c88993 Removing intermediate container 96bbe83de6ec Step 5/5 : CMD java -version ---> Running in f69b8d2a75b1 ---> bc8d54014325 Removing intermediate container f69b8d2a75b1 Successfully built bc8d54014325Copy the code

Execute Docker Images to see the image you just built

Execute the command

  • MVN Clean Package docker:build: Only the build operation is performed
  • MVN Clean Package docker: build-dpushimage After the build is completed, push the image
  • MVN Clean Package docker: build-dpushimageTag Executes build and pushes the image of the specified tag

Note: At least one imageTag must be specified here, which can be configured into the POM or specified on the command line.

The command line is specified as follows:

MVN Clean Package docker: build-dpushimagetags -DdockerImageTags=imageTag_1 -DdockerImageTags=imageTag_2

<build>
  <plugins>
    ...
    <plugin>
      <configuration>
        ...
        <imageTags>
           <imageTag>imageTag_1</imageTag>
           <imageTag>imageTag_2</imageTag>
        </imageTags>
      </configuration>
    </plugin>
    ...
  </plugins>
</build>
Copy the code

Bind Docker commands to Maven phases

  • You can bind Docker commands to various stages of Maven. We can divide Docker into build, tag, and push stages, and then bind Maven’s package and deploy stages respectively.

  • Just execute MVN deploy to complete the build, tag and push operations. When execute MVN build, only build and tag operations will be completed.

  • In addition, when we want to skip some steps or perform only one step, we don’t need to modify the POM file, we just need to specify to skip a docker step. For example, when our project has configured the automatic template, but this time we only need to hit the mirror to the local self-test.

  • If you don’t want to perform the push phase, you can skip the push operation by specifying -dskipdockerpush.

In the above example, when executing MVN package, execute build, tag, and when executing MVN deploy, execute build, tag, and push. If we want to skip a docker procedure, we just need:

  • -DskipDockerBuild Skips the build image
  • -DskipDockerTag Skips tag mirroring
  • -DskipDockerPush skips the push image
  • -DskipDocker skips an entire phase

For example, if we want to execute package without the tag process, we need MVN package-dskipDockerTag.

<build> <plugins> <plugin> <groupId>com.spotify</groupId> <artifactId>docker-maven-plugin</artifactId> The < version > 1.0.0 < / version > < configuration > < imageName > mavendemo < / imageName > < baseImage > Java < / baseImage > <maintainer>docker_maven [email protected]</maintainer> <workdir>/ROOT</workdir> <cmd>["java", "-version"]</cmd> <entryPoint>["java", "-jar", "${project.build.finalName}.jar"]</entryPoint> <resources> <resource> <targetPath>/ROOT</targetPath> <directory>${project.build.directory}</directory> <include>${project.build.finalName}.jar</include> </resource> </resources> </configuration> <executions> <execution> <id>build-image</id> <phase>package</phase> <goals> <goal>build</goal> </goals> </execution> <execution> <id>tag-image</id> <phase>package</phase> <goals> <goal>tag</goal> </goals> <configuration> <image>mavendemo:latest</image> <newName>docker.io/wanyang3/mavendemo:${project.version}</newName> </configuration> </execution> <execution> <id>push-image</id> <phase>deploy</phase> <goals> <goal>push</goal> </goals> <configuration> <imageName>docker.io/wanyang3/mavendemo:${project.version}</imageName> </configuration> </execution> </executions> </plugin> </plugins> </build>Copy the code

The Docker-Maven-plugin also provides many useful configurations, just to name a few parameters.

Security Authentication Configuration

When we push the image into the Docker warehouse, no matter it is public or private, security authentication is often required and the operation can be carried out after the login is completed. Of course, we can login with the docker login -u user_name -p password docker_registry_host command line, but for automated processes, this is not very convenient. Security authentication can be easily implemented using the Docker-Maven-plugin.

First, add related server configuration in Maven configuration file setting.xml, mainly configure the Docker Registry user authentication information.

<servers>
  <server>
    <id>my-docker-registry</id>
    <username>wanyang3</username>
    <password>12345678</password>
    <configuration>
      <email>[email protected]</email>
    </configuration>
  </server>
</servers>
Copy the code

Then just use the server ID in pom.xml.

<plugin> <plugin> <groupId>com.spotify</groupId> <artifactId>docker-maven-plugin</artifactId> <version>1.0.0</version> The < configuration > < imageName > registry.example.com/wanyang3/mavendemo:v1.0.0 < / imageName >... <serverId>my-docker-registry</serverId> </configuration> </plugin>Copy the code

Use private Docker repository addresses

In the actual working environment, we need to push the image into our private Docker repository, which is also easy to achieve by using the docker-Maven-plugin. There are several ways to achieve this:

Modify the imageName operation of the POM file

<configuration>
    <imageName>{privateImageHubUrl}/imageName/tag</imageName>
    ...
</configuration>
Copy the code

Output in the above format.

Modify the newName operation in the POM file

<configuration> <imageName>mavendemo</imageName> ... </configuration> <execution> <id>tag-image</id> <phase>package</phase> <goals> <goal>tag</goal> </goals> <configuration>  <image>mavendemo</image> <newName>{privateImageHubUrl}/imageName/tag</newName> </configuration> </execution>Copy the code

Restart the Docker service

systemctl stop docker
systemctl start docker
Copy the code

Enable the Docker build port for the firewall

firewall-cmd –zone=public –add-port=2375/tcp –permanentfirewall-cmd –reload