Prerequisites
- Docker Hub Account
- Docker and Git installed locally
- Familiarity with the Linux terminal
- Familiarity with text editors (vi, emacs, etc.)
Overview
At a high-level, containers are packaged software applications containing all of their dependencies like the operating system (OS), file structures, configuration and other code libraries.
Containers offer many benefits but here we list a few of the most impactful ones:
- Isolated Runtime Environments
- Two or more containers running on the same system do not affect one another.
- Portability
- The same container can be run on a laptop, on the cloud, or on TIDE without being modified.
- Consistency
- The same container given the same input will produce the same output.
Docker must be installed on your local machine to proceed. Learn how to install Docker
Steps to Run a Container
1. Define the Code to Run
This tutorial will use the GitHub repository hello-csu
for simple demonstration. Clone this repo to your local machine:
git clone https://github.com/csu-tide/hello-csu.git
cd hello-csu
2. Understand the Dockerfile
Use vi Dockerfile
to open the Dockerfile. You’ll see the following content:
FROM python:3
WORKDIR /usr/src/app
COPY hello.py /usr/src/app/hello.py
CMD ["python3", "hello.py"]
Here’s a breakdown of each line in this file:
- Defines a base image. In this case, the official Python3 image from Docker Hub
FROM python:3
- Sets the working directory inside the container to
usr/src/app
WORKDIR /usr/src/app
- Copies the python file from hello-csu to the container working directory
COPY hello.py /usr/src/app/hello.py
- Runs the hello.py file
CMD ["python3", "hello.py"]
3. Build the Docker Image
Using the above Dockerfile, build a Docker image with this command:
docker build -t testimage .
4. Run the Docker Container
Now that the image has been created from the Dockerfile, run a Docker container from the image:
docker run --name testcontainer testimage
NOTE: Since the only command in our image definition was to run the python file, the container stops automatically once that command completes.
This command will list the stopped container along with any others that have been created:
docker container ls -a
6. Push the Image to Docker Hub
- Login to Docker Hub
docker login
- Tag the Image
docker tag testimage your-dockerhub-username/testimage:latest
- Push the Image
docker push your-dockerhub-username/testimage:latest
Then navigate to your Docker Hub profile and look for the new image under the “Repositories” section
🎉 Congrats! 🎉 You’ve successfully built a Docker image from a Dockerfile, created a running Docker container from an image, and pushed that image to the Docker Hub Image Repository!