Docker for Developers

2022-01-18

Recently I started using Docker in my development workflow. Docker is a tool that allows us to package our application and all its dependencies into a container. A container is like a lightweight virtual machine, but instead of running a full operating system, it shares the host operating system and only includes what the application needs to run.

The Problem Docker Solves

One of the most common problems in software development is "it works on my machine". A developer might have a specific version of Node.js, a certain database version, and some environment variables configured on their machine. When another developer tries to run the same code, things break because their setup is different. Docker solves this by making sure the application runs in the same environment everywhere.

Dockerfile

To use Docker, we create a file called Dockerfile in our project. This file contains instructions on how to build the container image. For example, a simple Dockerfile for a Node.js application might look like this:

FROM node:16
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["npm", "start"]

Each line is an instruction. FROM sets the base image, WORKDIR sets the working directory inside the container, COPY copies files from our machine into the container, RUN executes a command during the build, EXPOSE tells Docker which port the app uses, and CMD defines the command to run when the container starts.

Docker Compose

When our application needs multiple services, for example a web app and a database, we can use Docker Compose. We define all the services in a docker-compose.yml file:

version: '3'
services:
  web:
    build: .
    ports:
      - "3000:3000"
  db:
    image: postgres:13
    environment:
      POSTGRES_PASSWORD: password

Then we run docker-compose up and both services start together. They can communicate with each other using the service name as the hostname.

Useful Commands

Some Docker commands that I use frequently: docker build -t myapp . to build an image, docker run -p 3000:3000 myapp to run a container, docker ps to list running containers, and docker stop to stop a container. Docker has made it much easier to set up development environments and share them with the team.