Swiftorial Logo
Home
Swift Lessons
Matchuup
CodeSnaps
Tutorials
Career
Resources

Docker Secrets

Docker Secrets allow you to securely store and manage sensitive information such as passwords, API keys, and certificates in a Docker Swarm. This guide covers key concepts, steps to create and manage Docker secrets, examples, and best practices for using Docker secrets with Express.js applications.

Key Concepts of Docker Secrets

  • Secret: A piece of sensitive data that is encrypted and stored securely in a Docker Swarm.
  • Docker Swarm: A cluster of Docker nodes where you can deploy services and manage secrets.
  • Service: A containerized application that can access secrets within a Docker Swarm.

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 docker-compose.yml

// .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 fs = require('fs');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
    const secret = fs.readFileSync('/run/secrets/my_secret', 'utf8');
    res.send(`Hello, Docker Secrets! Secret: ${secret}`);
});

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 . .

# Make port 3000 available to the world outside this container
EXPOSE 3000

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

Initializing a Docker Swarm

Initialize a Docker Swarm on your manager node:

// Initialize a Docker Swarm
docker swarm init

Creating a Docker Secret

Create a Docker secret to store sensitive information:

// Create a Docker secret
echo "my_secret_value" | docker secret create my_secret -

Creating a Docker Compose File

Create a docker-compose.yml file to define the services and secrets for your Docker stack:

Example: docker-compose.yml

// docker-compose.yml
version: '3.8'
services:
  web:
    image: your-dockerhub-username/my-express-app:latest
    ports:
      - "3000:3000"
    secrets:
      - my_secret
    deploy:
      replicas: 3
      update_config:
        parallelism: 2
        delay: 10s
      restart_policy:
        condition: on-failure
    networks:
      - webnet

secrets:
  my_secret:
    external: true

networks:
  webnet:

Deploying the Stack to the Swarm

Deploy the stack to the Docker Swarm using the docker stack deploy command:

// Deploy the stack to the swarm
docker stack deploy -c docker-compose.yml my_stack

// Check the status of the services
docker service ls

// Check the status of the tasks
docker service ps my_stack_web

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

Updating the Secret

Update the Docker secret if the value changes:

// Remove the old secret
docker secret rm my_secret

// Create a new secret with the updated value
echo "my_new_secret_value" | docker secret create my_secret -

Best Practices for Using Docker Secrets

  • Use Secrets for Sensitive Data: Store sensitive information such as passwords, API keys, and certificates in Docker secrets.
  • Limit Secret Scope: Only attach secrets to services that need them to minimize the risk of exposure.
  • Rotate Secrets Regularly: Regularly rotate secrets to enhance security.
  • Use Environment Variables for Development: Use environment variables to manage sensitive data during local development.
  • Secure Your Swarm: Use TLS to encrypt communication between nodes and services in your Docker Swarm.

Testing Docker Secret Integration

Test your Docker secret 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 the secret value', async () => {
        const response = await axios.get('http://localhost:3000');
        expect(response.data).to.contain('Secret: my_secret_value');
    });
});

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

// Run tests
// docker run -p 3000:3000 your-dockerhub-username/my-express-app:latest
// npm test

Key Points

  • Secret: A piece of sensitive data that is encrypted and stored securely in a Docker Swarm.
  • Docker Swarm: A cluster of Docker nodes where you can deploy services and manage secrets.
  • Service: A containerized application that can access secrets within a Docker Swarm.
  • Follow best practices for using Docker secrets, such as using secrets for sensitive data, limiting secret scope, rotating secrets regularly, using environment variables for development, and securing your swarm.

Conclusion

Docker secrets allow you to securely store and manage sensitive information in a Docker Swarm. By understanding and implementing the key concepts, steps, examples, and best practices covered in this guide, you can effectively use Docker secrets to manage your Express.js applications. Happy coding!