Home > database >  docker-compose entrypoint restart not stateless
docker-compose entrypoint restart not stateless

Time:10-14

When I restart a container with docker-compose up with an entrypoint it's not stateless, it keep the context of the previous execution of the entrypoint.

docker-compose file:

version: '3.8'

services:
  test:
    image: debian:buster-slim
    entrypoint: ["/entrypoint.sh"]
    volumes:
      - ./entrypoint.sh:/entrypoint.sh
    command: ["echo", "100"]

entrypoint.sh file:

#!/bin/bash
set -e
set -x

mkdir folder

exec "$@"

the first time it log

Creating network "test_compose_entrypoint_default" with the default driver
Creating test_compose_entrypoint_test_1 ... done
Attaching to test_compose_entrypoint_test_1
test_1  |   mkdir folder
test_1  |   exec echo 100
test_1  | 100

if I rerun a docker-compose up , the second time it log

Starting test_compose_entrypoint_test_1 ... done
Attaching to test_compose_entrypoint_test_1
test_1  |   mkdir folder
test_1  | mkdir: cannot create directory 'folder': File exists
test_compose_entrypoint_test_1 exited with code 1

If I run docker-compose down and then it work again, but impossible to run two times in a row.

CodePudding user response:

In fact, docker-compose restart tries re-running the main container process in the existing (stopped) container. docker-compose up will default to reusing an existing container, if one exists with the right configuration, even if it's stopped. This can be a problem for setups like what you show that have the reasonable expectation of starting in a clean environment.

One approach is to code defensively around the possibility of the directory already existing:

# Create `folder` only if it doesn't exist.  Could still fail
# if the directory is read-only, or if `folder` is a plain file.
test -d folder || mkdir folder

At a higher level, you could docker-compose rm the existing container before re-launching it, or if you don't mind restarting everything, docker-compose up --force-recreate. This approach isn't compatible with an automatic restart: policy, though.

  • Related