Thursday 21 May 2020

How to build a Dockerfile into an image, tag it and push it to Docker Hub

We use Dockerfiles to create images, along like blueprints to outline applications. In this post I am going to walk through:

  1. Create a Dockerfile
  2. Add a custom COPY directive
  3. Build a Dockerfile into an image
  4. Query and identify images on a Docker host
  5. Tag a Docker image on the Docker host
  6. Push a Docker image to Docker Hub
Below is an example of a Dockerfile, which is basically just an nginx web server, we can tell this as the FROM directive is pointing towards the nginx:latest image, which is stored on Docker Hub. This is the base image which will be used to build this Dockerfile. If this image does not exist on the Docker host, when we go to build the file Docker will automatically pull it down locally to the server. 

The WORKDIR allows as to change the working directory inside the container, as part of this example we are changing directory so that we can copy in a new index.html file to customise the landing page for nginx. 

The COPY directive allows us to copy a local index.html to our working directory. The custom index.html file is in the same folder as the Dockerfile, so the process will copy and replace the index.html from the local folder on the host and overwrite what is in /usr/share/nginx. 


# this shows how we can extend/change an existing official image from Docker Hub

FROM nginx:latest
# highly recommend you always pin versions for anything beyond dev/learn

WORKDIR /usr/share/nginx/html
# change working directory to root of nginx webhost
# using WORKDIR is preferred to using 'RUN cd /some/path'

COPY index.html index.html

# I don't have to specify EXPOSE or CMD because they're in my FROM


Now that we have a basic understanding of how the Dockerfile is structured we can build a new Docker image from the Dockerfile. 

From the Docker host cd to the directory which stores the Dockerfile (ensure the sample index.html is also available, as our Dockerfile copies and overwrites the default installed as part of nginx). 

This command builds the image from the Dockerfile, the . at the end of the line mean using the working directory. We are also giving the image a new rpb-web-custom. 

docker build -t rpb-web-custom .     

This command allows us to query the system and find all the images present on this host. 

docker image ls

We can see that the rpb-web-customer image now exists with an IMAGE ID. We need the Image ID for the next command to log a tag against the image. 


The following command tags our local image with a tag we can use when pushing the image to Docker Hub. 

docker tag 9b1ac3 ryanbetts/rpb-web-custom

The following command takes out locally tagged image and pushes it up to Docker Hub at ryanbetts/rpb-web-custom. 

docker push ryanbetts/rpb-web-custom