Video Lesson: Run Docker containers with high availability

Run Docker containers with high availability

Learn how to configure containers to restart automatically and maintain high availability when their processes exit.


Lesson Content

We’ll start with a small Node.js script, index.js, that prints hello world and exits after three seconds:

cat > index.js <<'EOF'
console.log('hello world');

setTimeout(() => process.exit(), 3000);
EOF

Create a Dockerfile that copies the script into the image and runs it:

cat > Dockerfile <<'EOF'
FROM mhart/alpine-node
COPY index.js .
CMD node index.js
EOF

Build the image with the name helloworld:

docker build -t helloworld .

Run a container named test1:

docker run --name test1 helloworld

The script exits after three seconds, so the container stops. Check its status with docker ps, filtering for test1:

docker ps -a --filter name=test1

The container is exited and is no longer running. To restart a container automatically whenever its main process exits, use the --restart=always option:

docker run --name test2 --restart=always helloworld

Inspect test2 to confirm that it is still running:

docker ps --filter name=test2

Docker restarts the container after the script exits, so it remains available.

Docker Compose provides another way to configure containers for high availability. Create a docker-compose.yml file with the helloworld service and set its restart policy to always:

cat > docker-compose.yml <<'EOF'
version: "3"

services:
  helloworld:
    image: helloworld
    restart: always
EOF

Start three instances of the service with Docker Compose:

docker-compose up --scale helloworld=3

Docker Compose creates three containers for the helloworld service. Because the service uses restart: always, each container restarts whenever the script exits, so all three instances remain available.

Maggie

Hey, I'm Maggie! 👋

Ask me anything.

Want to chat with Maggie?

Log in for AI tutor access.

Comments

Join the discussion!

Notes

Keep track of what you learn!