[DroneCI] How to Configure Pipeline to Build and Push Docker Image

Sometimes we need to build Dockerfile to the docker image and push it to registry in CI pipeline. For instance, my development environment is windows/amd64, but my VPS is linux/arm64. At the end, I want to host the service in my VPS. Thus, it will be easy to build the docker image inside the CI pipeline.

In this post, I will show how to configure the pipeline to build and push docker image in DroneCI, which is a self-service Continuous Integration platform for busy development teams.

Take a real case as the example. The project is a static website generated by Hugo and I need to host it in the docker container. Therefore, building the docker image in CI comes into the play.

Let’s create a file called .drone.yml under the root directory of the git repository. Add the below content into the file.

 1---
 2kind: pipeline
 3type: docker
 4name: hugo-build-deploy
 5
 6volumes:
 7- name: hugosource
 8  host:
 9    path: "/drone/src"
10- name: dockersock
11  host:
12    path: /var/run/docker.sock
13
14platform:
15  os: linux
16  arch: amd64
17
18steps:
19- name: hugo-build
20  image: klakegg/hugo:0.92.2
21  volumes:
22  - name: hugosource
23    path: "/src"
24  commands:
25    - hugo
26    - ls ./public  # ./public is the output folder for all static files generated by hugo
27
28- name: build-and-push-image
29  image: plugins/docker
30  volumes:
31  - name: hugosource
32    path: "/src"
33  - name: dockersock
34    path: "/var/run/docker.sock" # Mandatory
35  settings:
36    username: <dockerhub username>
37    password:
38      from_secret: docker_hub_pwd # Configure the secret in the Drone repository setting 
39    repo: <dockerhub user>/<repo>
40    tags: 0.0.1
41    dockerfile: ./build/Dockerfile # Where the Dockerfile is located in your git repository
42
43trigger:
44  branch:
45  - master

We can see that we take advantage of the docker plugins in the step build-and-push-image. Basically it will do the following in sequence.

  1. Build Dockerfile.
  2. Login the registry with provided credential setting.
  3. Push the built docker image in step 1 to the registry.

If this post helped you to solve a problem or provided you with new insights, please upvote it and share your experience in the comments below. Your comments can help others who may be facing similar challenges. Thank you!
Buy Me A Coffee
DigitalOcean Referral Badge
Sign up to get $200, 60-day account credit !