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);
EOFCreate 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
EOFBuild the image with the name helloworld:
docker build -t helloworld .Run a container named test1:
docker run --name test1 helloworldThe script exits after three seconds, so the container stops. Check its status with docker ps, filtering for test1:
docker ps -a --filter name=test1The 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 helloworldInspect test2 to confirm that it is still running:
docker ps --filter name=test2Docker 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
EOFStart three instances of the service with Docker Compose:
docker-compose up --scale helloworld=3Docker 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.
Join the discussion!
Comments
Want to comment on this lesson?
Log in to leave comments.