Swiftorial Logo
Home
Swift Lessons
Matchuup
CodeSnaps
Tutorials
Career
Resources

Running Docker Containers

Running Docker containers allows you to start and manage your application in isolated environments. This guide covers key concepts, steps to run and manage Docker containers, examples, and best practices for running Docker containers with Express.js applications.

Key Concepts of Running Docker Containers

  • Container: A lightweight, standalone, executable package that includes everything needed to run a piece of software.
  • Image: A read-only template used to create containers.
  • Port Binding: Mapping a port on the host to a port on the container to allow external access.
  • Volume: A mechanism to persist data generated by and used by Docker containers.
  • Environment Variable: A variable that provides configuration information to a running container.

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 3000 to the outside world
EXPOSE 3000

# Run app when the container launches
CMD ["node", "src/index.js"]

Building the Docker Image

Build the Docker image for your Express application:

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

// List Docker images to verify the build
docker images

Running the Docker Container

Run the Docker container from the built image:

// 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 your containers:

Listing Running Containers

// List running containers
docker ps

Stopping a Running Container

// Stop a running container
docker stop 

Removing a Container

// Remove a container
docker rm 

Running a Container in Detached Mode

// Run a container in detached mode
docker run -d -p 3000:3000 my-express-app

Viewing Container Logs

// View logs of a running container
docker logs 

Using Volumes with Docker Containers

Persist data generated by and used by Docker containers using volumes:

// Run a container with a volume
docker run -p 3000:3000 -v $(pwd)/src:/usr/src/app/src my-express-app

// Modify the application source code and see the changes without rebuilding the image

Using Environment Variables with Docker Containers

Provide configuration information to a running container using environment variables:

// Run a container with environment variables
docker run -p 3000:3000 -e NODE_ENV=production my-express-app

Using Docker Compose to Manage Containers

Set up Docker Compose to manage multi-container applications:

Example: docker-compose.yml

// docker-compose.yml
version: '3.8'
services:
  web:
    build: .
    ports:
      - "3000:3000"
    volumes:
      - .:/usr/src/app
    environment:
      - NODE_ENV=development
// Run Docker Compose
docker-compose up --build

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

Best Practices for Running Docker Containers

  • Use Volumes for Data Persistence: Use volumes to persist data generated by and used by Docker containers.
  • Run Containers in Detached Mode: Use detached mode to run containers in the background.
  • Monitor Container Logs: Regularly monitor container logs to ensure your application is running correctly.
  • Use Environment Variables for Configuration: Store configuration data in environment variables to keep your application flexible and secure.
  • Keep Containers Lightweight: Ensure your containers are lightweight by minimizing the number of layers and removing unnecessary files.

Testing Docker Container Integration

Test your Docker container 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 build -t my-express-app .
// docker run -p 3000:3000 my-express-app
// npm test

Key Points

  • Container: A lightweight, standalone, executable package that includes everything needed to run a piece of software.
  • Image: A read-only template used to create containers.
  • Port Binding: Mapping a port on the host to a port on the container to allow external access.
  • Volume: A mechanism to persist data generated by and used by Docker containers.
  • Environment Variable: A variable that provides configuration information to a running container.
  • Follow best practices for running Docker containers, such as using volumes for data persistence, running containers in detached mode, monitoring container logs, using environment variables for configuration, and keeping containers lightweight.

Conclusion

Running Docker containers allows you to start and manage your application in isolated environments. By understanding and implementing the key concepts, steps, examples, and best practices covered in this guide, you can effectively run Docker containers for your Express.js applications. Happy coding!