Getting started with Docker
Table of contents:
Docker is a product that offers hardware virtualization at the operating system (OS) level. This ability allows developers to package software and its dependencies in order to ship it as containers.
An image is a software package that includes the source code and all required dependencies for the software to run. In Docker, an image is generated by the build command.
A container is a running instance of an image. In Docker, containers are executed using the run command.
This guide introduces you to Docker and how to use it to package and run applications. It assumes you are familiar with the LINUX environment and can comfortably interact with the Linux bash environment.
Installation and Setup
To download and set up Docker, run the command below in your terminal.
sudo apt-get update
sudo apt-get install docker-ce docker-ce-cli containerd.io
Basic Docker Commands
docker --version
- indetyfies currently installed version of Docker on the host system
docker ps
- list all running containers
docker image
- list locally stored images
docker login
- login into Dockerhub
docker push <username/images>
- allows to upload an image to your remote Dockerhub repository
docker pull <imagename>
- dowloads images from Dockrhub
docker build <path/to/docker/file>
- generates an image from the specified Docker image
docker run -it -d <imagename>
- create a container from the built image
docker stop <container id>
- allows to halt the running of the defined container
docker rm <container id>
- allows to delete a stopped container
docker rmi <imageid>
- allows to delete the specified image ID from local storage
Sample Script
To demonstrate Docker in action, run a sample Flask script within Docker.
from flask import Flask
server = Flask(__name__)
@server.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
server.run(host='0.0.0.0')
Dockerfile:
# set base image (host OS)
FROM python:3.8
# set the working directory in the container
WORKDIR /code
COPY . .
RUN pip install flask
# command to run on container start
CMD [ "python", "./app.py" ]
To build and run application use:
docker build -t myimage .
After the Docker image is built, it is time to run it. Since this is a Flask application that runs on a certain port, provide the port number via the ports(-p) flag.
docker run -p 5000:5000 myimage
The app is now running at the localhost address: http://0.0.0.0:5000
.
Reference:
My site is free of ads and trackers. Was this post helpful to you? Why not
Disqus is great for comments/feedback but I had no idea it came with these gaudy ads.