Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Docker Containers

Docker containers are lightweight, standalone, and executable packages that include everything needed to run a piece of software, including code, runtime, system tools, libraries, and settings. This guide covers key concepts, steps to create and manage Docker containers, examples, and best practices for using Docker containers with Express.js applications.

Key Concepts of Docker Containers

  • Docker Container: A lightweight, standalone, and executable package that includes everything needed to run a piece of software.
  • Docker Image: A read-only template used to create containers. Images are built from Dockerfiles.
  • Container Lifecycle: The states of a Docker container from creation to termination (create, start, stop, restart, pause, unpause, kill, and remove).
  • Container Volumes: Persistent storage for Docker containers.
  • Networking: Configuring network settings for Docker containers to communicate with each other and the outside world.

Setting Up the Project

Initialize a new Express.js project and create a Dockerfile:

// Initialize a new project
// npm init -y

// Install Express
// npm install express

// Create the project structure
// mkdir src
// touch src/index.js Dockerfile .dockerignore .gitignore

// .gitignore
node_modules
.env

// .dockerignore
node_modules
npm-debug.log

Creating an Express Application

Create a simple Express application:

Example: index.js

// src/index.js
const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
    res.send('Hello, Docker Containers!');
});

app.listen(port, () => {
    console.log(`Server running at http://localhost:${port}/`);
});

Creating a Dockerfile

Create a Dockerfile to containerize your Express application:

Example: Dockerfile

// Dockerfile
FROM node:14

# Create app directory
WORKDIR /usr/src/app

# Install app dependencies
COPY package*.json ./
RUN npm install

# Bundle app source
COPY . .

# Expose port and start application
EXPOSE 3000
CMD ["node", "src/index.js"]

Building and Running the Docker Container

Build and run the Docker container for your Express application:

// Build the Docker image
docker build -t my-express-app .

// Run the Docker container
docker run -p 3000:3000 my-express-app

// Open http://localhost:3000 in your browser to see the application running

Managing Docker Containers

Use Docker commands to manage the lifecycle of your Docker containers:

List Running Containers

// List running containers
docker ps

Start a Container

// Start a container
docker start 

Stop a Container

// Stop a container
docker stop 

Restart a Container

// Restart a container
docker restart 

Remove a Container

// Remove a container
docker rm 

Using Volumes for Persistent Storage

Use Docker volumes to persist data generated by and used by Docker containers:

Create a Volume

// Create a volume
docker volume create my_volume

Run a Container with a Volume

// Run a container with a volume
docker run -p 3000:3000 -v my_volume:/usr/src/app my-express-app

Networking Docker Containers

Configure network settings to allow Docker containers to communicate with each other and the outside world:

List Networks

// List networks
docker network ls

Create a Network

// Create a network
docker network create my_network

Run a Container with a Network

// Run a container with a network
docker run -p 3000:3000 --network my_network my-express-app

Best Practices for Using Docker Containers

  • Keep Containers Lightweight: Use minimal base images and avoid installing unnecessary software inside containers.
  • Use Volumes for Data Persistence: Use Docker volumes to persist data and avoid data loss when containers are removed.
  • Isolate Applications: Run each application in a separate container to improve security and maintainability.
  • Monitor Containers: Use monitoring tools to track the performance and health of your containers.
  • Automate Container Management: Use orchestration tools like Docker Compose, Kubernetes, or Docker Swarm to manage complex containerized applications.

Testing Docker Container Integration

Test your Docker container setup to ensure it works correctly:

Example: Testing with Mocha and Chai

// Install Mocha and Chai
// npm install --save-dev mocha chai

// test/app.test.js
const chai = require('chai');
const expect = chai.expect;
const axios = require('axios');

describe('Express App', () => {
    it('should return Hello, Docker Containers!', async () => {
        const response = await axios.get('http://localhost:3000');
        expect(response.data).to.equal('Hello, Docker Containers!');
    });
});

// Add test script to package.json
// "scripts": {
//   "test": "mocha"
// }

// Run tests
// docker run -p 3000:3000 my-express-app
// npm test

Key Points

  • Docker Container: A lightweight, standalone, and executable package that includes everything needed to run a piece of software.
  • Docker Image: A read-only template used to create containers. Images are built from Dockerfiles.
  • Container Lifecycle: The states of a Docker container from creation to termination (create, start, stop, restart, pause, unpause, kill, and remove).
  • Container Volumes: Persistent storage for Docker containers.
  • Networking: Configuring network settings for Docker containers to communicate with each other and the outside world.
  • Follow best practices for using Docker containers, such as keeping containers lightweight, using volumes for data persistence, isolating applications, monitoring containers, and automating container management.

Conclusion

Docker containers are essential for creating and managing applications in a consistent and efficient manner. By understanding and implementing the key concepts, steps, examples, and best practices covered in this guide, you can effectively use Docker containers to manage your Express.js applications. Happy coding!