Sitemap

Streamline Your Local Development with Docker

6 min readApr 27, 2023
Press enter or click to view image in full size

Introduction

In the last decade, Docker has completely changed the dynamics of software development. One of the significant issues in writing production codes is portability. The classic problem of “If it works on my computer, why doesn’t it work on yours?”. Docker popularized the concept of containers. A container is a virtualized operating system that can run anything, a microservice or an entire application. A container packs all the necessary executables, dependencies and configuration files in an isolated environment. This makes any dockerized application easy to deploy.

Docker containers provide the best out-of-the-box isolation in the market along with a virtualized OS, which makes them ideal for setting up a development environment.

Why use Docker for development?

Let us see what benefits you will get by using Docker for local development.

Isolation: Docker provides a very convenient isolated environment for software development. Each container resembles a separate Linux machine, so you get all the benefits of a standalone machine, a separate operating system, a terminal and a file system. A completely isolated environment for all your dependencies makes the development environment clean and precise.

Portability: Docker containers are highly portable. You can either ship an entire application as a single container or develop a complete application with multiple containers and deploy them as a single service. Containers come with all the dependencies and executables; they will have no problem running on different environments (desktop or cloud). So no more worrying if your code will run on another machine just as smoothly as on yours.

Convenience: The foremost benefit of using Docker for local development is less work overhead. If you want to deploy any application, probably the ideal way is to containerize it and deploy it on the server. While creating containers, you might encounter bugs or any other inconsistencies you missed while coding your app. In this situation, you need to rebuild the images after correction, which is a nuisance. But instead, you can open your project directory inside a container and edit code files directly. This saves a lot of time and energy.

Create an API

This is our project directory structure.

.
├── Dockerfile
├── requirements.txt
└── src
├── main.py

For this article, we will create a simple Fast API application. First, create a sub-folder in the parent folder to store the code file write codes. Here is a simple Fast API code snippet.

from fastapi import FastAPI
app = FastAPI()
@app.get("/")
asyncdefroot():
return {"message": "Hello World! sunil"}

As we will be working with Docker, create requirements text file.

fastapi
uvicorn
#you can mention any specific version as well123bash

Now, we define our Dockerfile. A docker file is a text file that explains how to configure a docker container.

FROM python:3.10-slim
WORKDIR /code
COPY ./requirements.txt /code/requirements.txt
RUN pip install - no-cache-dir - upgrade -r /code/requirements.txt
COPY ./src /code/src
CMD ["uvicorn", "src.main:app", " - host", "0.0.0.0", " - port", "80", " - reload"]1234567891011bash

Let’s break apart each line.

  • FROM: This is the base image. A slim base image to create a compact image.
  • WORKDIR: The working directory inside a container where the codes will be saved
  • COPY: Copying files from the local directory to the working directory.
  • RUN: Run any Linux commands that will build the image.
  • CMD: The commands are used when a container is created out of the image.

Creating a Container

To get Docker on your system, you can either install the Docker engine or the Docker desktop. I prefer Docker desktop as it provides a beautiful user interface to interact with images, containers and volumes. You also get Kubernetes services, which may come in handy in future.

First, build an image out of the Dockerfile.

docker build -t demo-image .

After a few seconds, your image will be ready. Now we will create a container.

docker run — name my-container -p 80:80 demo-image

Head over to http:localhost:80 on your browser. This will show our message.

So far, so good. One drawback of this approach is that the codes inside containers cannot be changed from IDE. To do that, you will have to get inside the container terminal and edit it yourself via an editor like Vi. Some Linux images don’t come bundled with Vim editors. In most cases, You need to rebuild the images.

But there is a solution you can use Docker volumes. Volumes are the mechanism to persist data generated by containers. Defining volume mapping while creating a container will ensure the changes to the code files are reflected in the API. To do this, you need to map your project folder to the working directory folder while creating the container. The command for the same is

docker run — name my-container2 -p 80:80 -v <path to project folder>:/code my-image

Now, this will ensure any changes to your code files are reflected in your API. Try tweaking your code and reloading the localhost page changes will be visible.

With Dev Containers

What if I tell you there is an even better way to set up your local development environment with Docker? The current solution is good but still lacks a lot. For example, the IDE will not detect any packages installed, so you will not get the benefits of autocompletion, details of methods and classes and other IDE-exclusive benefits. This can be frustrating while writing codes. To avoid this issue we have a tool called Dev containers.

The Dev containers is a tool by Microsoft that lets us open any folder or file inside a Docker container.

To set this up in your Visual Studio Code IDE, install Docker and Dev container extensions.

Press enter or click to view image in full size

The next step is to open our folder in a container. You can choose to either connect it to a running container or create a new one.

To do this open your command palette (ctrl + shift + p) and search for Dev containers.

Press enter or click to view image in full size

This will open a new VS code window with your project folder inside the container.

Press enter or click to view image in full size

You can see in the bottom left in green that indicates it is running inside a container. You still have to install extensions inside the container to take full benefit of the setup. You will only have to do it once.

Multiple Containers

To define multiple containers, we will use docker-compose.yaml file. It is a configuration file that allows you to define multiple containers as a single service.

So, let’s define a Redis service along with our Fast API app. Redis is an in-memory data structure tool used as an in-memory database or for caching. We will use Redis to count the number of hits on our server. To define a Redis service all we need to do is pull it from the Docker Hub registry.

#main.pyfrom fastapi import FastAPI
from redis import Redis
app = FastAPI()
r = Redis(host="redis", port=6379)
@app.get("/")asyncdefroot():
return {"message": "Hello World!"}
@app.get("/hits")asyncdefroot():
r.incr("hits")
return {"Number of hits:": r.get("hits")}123456789101112131415python

YAML file for Docker compose

services:
app:
build: .
container_name: fastapi-server
command: uvicorn src.main:app --host 0.0.0.0 --port 80 --reload
ports:
- 80:80
- 5678:5678
volumes:
- .:/code
depends_on:
- redis

redis:
image: redis:alpine

Now, run

docker compose up - build -d

This will create the containers. Repeat the previous steps to connect to the fastapi-server container and download extensions.

You can visit the endpoint “localhost:80/hits” and see the count increasing with every refresh.

Conclusion

Using Docker for local development makes the codebase consistent, concise, and portable. Whether you deploy or not, containers make a great development environment.

So, this was all about setting up your local development environment with Docker.

Hope you liked the article. Happy coding.

--

--

sunilkumardash
sunilkumardash

Written by sunilkumardash

Developer, Writer and a culture buff.