How to K8s: Pull, Edit, and Push a Docker Image
In order to access a Docker container of your own design in Kubernetes, you’ll likely first have to push the container’s image to Docker Hub, because by default, Kubernetes wants to pull any images defined in its YAML file from Docker Hub. Today, we’ll run through the basics to get you started.
It is worth noting that creating a Dockerfile will allow you to easily document, build, and manage your images, but we’ll start off with a look at a quick method for testing purposes.
First, you’ll need to install Docker locally. Once you have Docker installed, you’ll be able to pull any image you like from the massive number of resources available in Docker Hub. Once you’ve found the base image you’d like to build upon, you can simply run:
docker pull <image_name>
For the sake of a working example, let’s go ahead and pull the latest Ubuntu image:
docker pull ubuntu:latest
This will pull the image from Docker Hub down to your local machine. To spin up the Docker container and gain access to a pseudo-terminal running therein, simply run:
docker run -it ubuntu
This will give you root access to the running container. From there, you will be able to make changes to the Docker container. These changes can be anything you like – configuration of resources already in the container, installation of new resources, or even newly written code. Just for the fun of it, let’s install Python in our newly spun up container.
apt-get install python3
Then, after exiting the running container, you will need to create an account on Docker Hub, and then log in from the command line with your newly minted credentials, like so:
Login with your Docker ID to push and pull images from Docker Hub. If you don't have a Docker ID, head over to https://hub.docker.com to create one.
Once you’ve entered your credentials, you will need to create a repository within your Docker Hub account. To do this, you’ll need to use the Docker Hub UI.
Next, we’ll need to get the ID of the container in which we updated the base Ubuntu image, like so:
docker ps -a
CONTAINER ID IMAGE COMMAND CREATED
1459bfefa0de ubuntu "/bin/bash" 42 minutes ago
STATUS PORTS NAMES
Up 42 minutes 0.0.0.0:8888->8888/tcp blissful_lamarr
With the container’s ID in hand, we can now commit our changes locally:
docker commit 1459bfefa0de jdvincent/ubuntu-python3.8
And finally, you can push the image to Docker Hub with the following:
docker push jdvincent/ubuntu-python3.8
And voila! The updated image (jdvincent/ubuntu-python3.8) can now be passed in any Kubernetes YAML file, and it will be available to Kubernetes!
By default, Kubernetes looks for Docker images in Docker Hub. In order to make changes to the Docker image you’d like to use in Kubernetes, you’ll most likely need to commit an image locally, and then push that image up to Docker Hub.