Docker Tutorial — Getting Started with Python, Redis, and Nginx.

Django Stars
HackerNoon.com
19 min readMar 24, 2017

--

This is an introductory tutorial on Docker containers. By the end of this article, you will know how to use Docker on your local machine. Along with Python, we are going to run Nginx and Redis containers. Those examples assume that you are familiar with the basic concepts of those technologies. There will be lots of shell examples, so go ahead and open the terminal.

Note: the code samples may be displayed improperly because of markdown. I recommend to continue reading the original article on our blog to make sure all the examples are displayed properly.

What is Docker?

Docker is an open-source tool that automates the deployment of an application inside a software container. The easiest way to grasp the idea behind Docker is to compare it to, well… standard shipping containers.

Back in the day, transportation companies faced the following challenges:

  • How to transport different (incompatible) types of goods side by side (like food and chemicals, or glass and bricks).
  • How to handle packages of various sizes using the same vehicle.

After the introduction of containers, bricks could be put over glass, and chemicals could be stored next to food. Cargo of various sizes can be put inside a standardized container and loaded/unloaded by the same vehicle.

Let’s go back to containers in software development.

When you develop an application, you need to provide your code along with all possible dependencies like libraries, the web server, databases, etc. You may end up in a situation when the application is working on your computer, but won’t even start on the staging server, or the dev or QA’s machine.

This challenge can be addressed by isolating the app to make it independent of the system.

How does this differ from virtualization?

Traditionally, virtual machines were used to avoid this unexpected behavior. The main problem with VM is that an “extra OS” on top of the host operating system adds gigabytes of space to the project. Most of the time your server will host several VMs that will take up even more space. And by the way, at the moment, most cloud-based server providers will charge you for that extra space. Another significant drawback of VM is a slow boot.

Docker eliminates all the above by simply sharing the OS kernel across all the containers running as separate processes of the host OS.

Keep in mind that Docker is not the first and not the only containerization platform. However, at the moment Docker is the biggest and the most powerful player on the market.

Why do we need Docker?

The short list of benefits includes:

  • Faster development process
  • Handy application encapsulation
  • The same behaviour on local machine / dev / staging / production servers
  • Easy and clear monitoring
  • Easy to scale

Faster development process

There is no need to install 3rd-party apps like PostgreSQL, Redis, Elasticsearch on the system — you can run it in containers. Docker also gives you the ability to run different versions of same application simultaneously. For example, say you need to do some manual data migration from an older version of Postgres to a newer version. You can have such a situation in microservice architecture when you want to create a new microservice with a new version of the 3rd-party software.

It could be quite complex to keep two different versions of the same app on one host OS. In this case, Docker containers could be a perfect solution — you receive isolated environments for your applications and 3rd-parties.

Handy application encapsulation

You can deliver your application in one piece. Most programming languages, frameworks and all operating systems have their own packaging managers. And even if your application can be packed with its native package manager, it could be hard to create a port for another system.

Docker gives you a unified image format to distribute you applications across different host systems and cloud services. You can deliver your application in one piece with all the required dependencies (included in an image) ready to run.

Same behaviour on local machine / dev / staging / production servers

Docker can’t guarantee 100% dev / staging / production parity, because there is always the human factor. But it reduces to almost zero the probability of error caused by different versions of operating systems, system-dependencies, etc.

With right approach to building Docker images, your application will use the same base image with the same OS version and the required dependencies.

Easy and clear monitoring

Out of the box, you have a unified way to read log files from all running containers. You don’t need to remember all the specific paths where your app and its dependencies store log files and write custom hooks to handle this.
You can integrate an external logging driver and monitor your app log files in one place.

Easy to scale

A correctly wrapped application will cover most of the Twelve Factors. By design, Docker forces you follow its core principles, such as configuration over environment variables, communication over TCP/UDP ports, etc. And if you’ve done your application right, it will be ready for scaling not only in Docker.

Supported platforms

Docker’s native platform is Linux, as it’s based on features provided by the Linux kernel. However, you can still run it on macOS and Windows. The only difference is that on macOS and Windows, Docker is encapsulated into a tiny virtual machine. At the moment, Docker for macOS and Windows has reached a significant level of usability and feels more like a native app.

Installation

You can check out the installation instructions for Docker here.
If you’re running Docker on Linux, you need to run all the following commands as root or add your user to docker group and re-login:

Terminology

  • Container — a running instance that encapsulates required software. Containers are always created from images. A container can expose ports and volumes to interact with other containers or/and the outer world. Containers can be easily killed / removed and re-created again in a very short time. Containers don’t keep state.
  • Image — the basic element for every container. When you create an image, every step is cached and can be reused (Copy On Write model). Depending on the image, it can take some time to build. Containers, on the other hand, can be started from images right away.
  • Port — a TCP/UDP port in its original meaning. To keep things simple, let’s assume that ports can be exposed to the outer world (accessible from the host OS) or connected to other containers — i.e., accessible only from those containers and invisible to the outer world.
  • Volume — can be described as a shared folder. Volumes are initialized when a container is created. Volumes are designed to persist data, independent of the container’s lifecycle. Registry — the server that stores Docker images. It can be compared to Github — you can pull an image from the registry to deploy it locally, and push locally built images to the registry.
  • Docker Hub — a registry with web interface provided by Docker Inc. It stores a lot of Docker images with different software. Docker Hub is a source of the “official” Docker images made by the Docker team or in cooperation with the original software manufacturer (it doesn’t necessary mean that these “original” images are from official software manufacturers). Official images list their potential vulnerabilities. This information is available to any logged-in user. There are both free and paid accounts available. You can have one private image per account and an infinite amount of public images for free. Also there is a Docker Store — a service very similar to Docker Hub. It’s a marketplace with ratings, reviews, etc. My personal opinion is that it’s marketing stuff. I’m totally happy with Docker Hub.

Example 1: hello world

It’s time to run your first container:

Console output:

  • docker run is a command to run a container.
  • ubuntu is the image you run. For example, the Ubuntu operating system image. When you specify an image, Docker looks first for the image on your Docker host. If the image does not exist locally, then the image is pulled from the public image registry — Docker Hub.
  • /bin/echo ‘Hello world’ is the command that will run inside a new container. This container simply prints “Hello world” and stops the execution.

Let’s try to create an interactive shell inside a Docker container:

  • -t flag assigns a pseudo-tty or terminal inside the new container.
  • -i flag allows you to make an interactive connection by grabbing the standard input (STDIN) of the container.
  • — rm flag automatically removes the container when the process exits. By default, containers are not deleted. This container exists until we keep the shell session and terminates when we exit the session (like an SSH session with a remote server).

If you want to keep the container running after the end of the session, you need to daemonize it:

  • — name daemon assigns daemon name to a new container. If you don’t specify a name explicitly, Docker will generate and assign it automatically.
  • -d flag runs the container in the background (i.e., daemonizes it).

Let’s see what containers we have at the moment:

Console output:

  • docker ps is a command to list containers.
  • -a shows all containers (without -a flag ps will show only running containers).

The ps shows us that we have two containers:
* gifted_nobel (the name for this container was generated automatically — it will be different on your machine). It’s the first container we created, the one that printed ‘Hello world’ once. * daemon — the third container we created, which runs as a daemon.

Note: there is no second container (the one with interactive shell) because we set the — rm option. As a result, this container is automatically deleted right after execution.

Let’s check the logs and see what the daemon container is doing right now:

Console output:

  • docker logs fetch the logs of a container.
  • -f flag to follow the log output (works actually like tail -f).

Now let’s stop the daemon container:

Make sure the container has stopped.

Console output:

The container is stopped. We can start it again:

Let’s ensure that it’s running:

Console output:

Now, stop it again and remove all the containers manually:

To remove all containers, we can use the following command:

  • docker rm is the command to remove the container.
  • -f flag (for rm) stops the container if it’s running (i.e., force deletion).* -q flag (for ps) is to print only container IDs.

You May Also Like:

Example 2: Environment variables and volumes

Starting from this example, you’ll need several additional files you can find on my GitHub repo. You can clone my repo or simply use the following link to download the sample files.

It’s time to create and run more a meaningful container, like Nginx.
Change the directory to examples/nginx:

Warning: This command looks quite heavy, but it’s just an example to explain volumes and env variables. In 99% of real-life cases, you won’t start Docker containers manually — you’ll use orchestration services (we’ll cover docker-compose in example #4) or write a custom script to do it.

Console output:

  • -p is a ports mapping HOST PORT:CONTAINER PORT.
  • -v is a volume mounting HOST DIRECTORY:CONTAINER DIRECTORY.

Important: run command accepts only absolute paths. In our example, we’ve used $(pwd) to set the current directory absolute path.
Now check this url in your web browser.

We can try to change /example/nginx/index.html (which is mounted as a volume to /usr/share/nginx/html directory inside the container) and refresh the page.

Let’s get the information about the test-nginx container:

This command displays system-wide information about the Docker installation. This information includes the kernel version, number of containers and images, exposed ports, mounted volumes, etc.

Example 3: Writing your first Dockerfile

To build a Docker image, you need to create a Dockerfile. It is a plain text file with instructions and arguments. Here is the description of the instructions we’re going to use in our next example:

  • FROM — set base image
  • RUN — execute command in container
  • ENV — set environment variable
  • WORKDIR — set working directory
  • VOLUME — create mount-point for a volume
  • CMD — set executable for container

You can check Dockerfile reference for more details.

Let’s create an image that will get the contents of the website with url and store it to the text file. We need to pass the website url via the environment variable SITE_URL. The resulting file will be placed in a directory, mounted as a volume.

Place the file name Dockerfile in examples/curl directory with the following contents:

Dockerfile is ready. It’s time to build the actual image.

Go to examples/curl directory and execute the following command to build an image:

Console output:

  • docker build command builds a new image locally.
  • -t flag sets the name tag to an image.

Now we have the new image, and we can see it in the list of existing images:

Console output:

We can create and run the container from the image. Let’s try it with the default parameters:

To see the results saved to file, run:

Let’s try with Facebook.com:

To see the results saved to file, run:

What Best practices for creating images

  • Include only necessary context — use a .dockerignore file (like .gitignore in git)
  • Avoid installing unnecessary packages — it will consume extra disk space.
  • Use cache. Add context that changes a lot (for example, the source code of your project) at the end of Dockerfile — it will utilize Docker cache effectively.
  • Be careful with volumes. You should remember what data is in volumes. Because volumes are persistent and don’t die with the containers, the next container will use data from the volume created by the previous container.
  • Use environment variables (in RUN, EXPOSE, VOLUME). It will make your Dockerfile more flexible.

Alpine images

A lot of Docker images (versions of images) are created on top of Alpine Linux — this is a lightweight distro that allows you to reduce the overall size of Docker images.

I recommend that you use images based on Alpine for third-party services, such as Redis, Postgres, etc. For your app images, use images based on buildpack — it will be easy to debug inside the container, and you’ll have a lot of pre-installed system-wide requirements.

Only you can decide which base image to use, but you can get the maximum benefit by using one basic image for all images, because in this case the cache will be used more effectively.

Example 4: Connection between containers

Docker compose — is an CLI utility used to connect containers with each other. You can install docker-compose via pip:

In this example, I am going to connect Python and Redis containers.

Go to examples/compose and execute the following command:

Console output:

The current example will increment view counter in Redis. Open the following url in your web browser and check it.

How to use docker-compose is a topic for a separate tutorial. To get started, you can play with some images from Docker Hub. If you want to create your own images, follow the best practices listed above. The only thing I can add in terms of using docker-compose is that you should always give explicit names to your volumes in docker-compose.yml (if the image has volumes). This simple rule will save you from an issue in the future when you’ll be inspecting your volumes.

In this case, redis_data will be the name inside the docker-compose.yml file; for the real volume name, it will be prepended with project name prefix.

To see volumes, run:

Console output:

Without an explicit volume name, there will be a UUID. Here’s an example from my local machine:

Docker way

Docker has some restrictions and requirements, depending on the architecture of your system (applications that you pack into containers). You can ignore these requirements or find some workarounds, but in this case, you won’t get all the benefits of using Docker. My strong advice is to follow these recommendations:

  • 1 application = 1 container.
  • Run the process in the foreground (don’t use systemd, upstart or any other similar tools).
  • Keep data out of containers — use volumes. Do not use SSH (if you need to step into container, you can use the docker exec command).
  • Avoid manual configurations (or actions) inside container.

Conclusion

To summarize this tutorial, alongside with IDE and Git, Docker has become a must-have developer tool. It’s a production-ready tool with a rich and mature infrastructure.

Docker can be used on all types of projects, regardless of size and complexity. In the beginning, you can start with compose and Swarm. When the project grows, you can migrate to cloud services like Amazon Container Services or Kubernetes.

Like standard containers used in cargo transportation, wrapping your code in Docker containers will help you build faster and more efficient CI/CD processes. This is not just another technological trend promoted by a bunch of geeks — it’s a new paradigm that is already being used in the architecture of large companies like PayPal, Visa, Swisscom, General Electric, Splink, etc.

The article is written by Alexander Ryabtsev (ALEXANDER RYABTSEV) — a backend engineer at Django Stars. Read more about docker on Django Stars blog.

Specially shared with Hackernoon community.

You are always welcome to ask questions and share topics you want to read about!

Have you already used Docker on your project? Leave us a comment or ask questions below!

If you find this post useful, please tap 👏 button below :)

Hacker Noon is how hackers start their afternoons. We’re a part of the @AMI family. We are now accepting submissions and happy to discuss advertising & sponsorship opportunities.

If you enjoyed this story, we recommend reading our latest tech stories and trending tech stories. Until next time, don’t take the realities of the world for granted!

--

--

Django Stars
HackerNoon.com

Guides and recommendations on how to transform ideas into digital products people want to use.