|
| 1 | +--- |
| 2 | +title: Using lifecycle hooks with Compose |
| 3 | +linkTitle: Use lifecycle hooks |
| 4 | +weight: 20 |
| 5 | +desription: How to use lifecycle hooks with Docker Compose |
| 6 | +keywords: cli, compose, lifecycle, hooks reference |
| 7 | +--- |
| 8 | + |
| 9 | +## Services lifecycle hooks |
| 10 | + |
| 11 | +When Docker Compose runs a container, it uses two elements, |
| 12 | +[ENTRYPOINT and COMMAND](https://github.com/manuals//engine/containers/run.md#default-command-and-options), |
| 13 | +to manage what happens when the container starts and stops. |
| 14 | + |
| 15 | +However, it can sometimes be easier to handle these tasks separately with lifecycle hooks - |
| 16 | +commands that run right after the container starts or just before it stops. |
| 17 | + |
| 18 | +Lifecycle hooks are particularly useful because they can have special privileges |
| 19 | +(like running as the root user), even when the container itself runs with lower privileges |
| 20 | +for security. This means that certain tasks requiring higher permissions can be done without |
| 21 | +compromising the overall security of the container. |
| 22 | + |
| 23 | +### Post-start hooks |
| 24 | + |
| 25 | +Post-start hooks are commands that run after the container has started, but there's no |
| 26 | +set time for when exactly they will execute. The hook execution timing is not assured during |
| 27 | +the execution of the container's `entrypoint`. |
| 28 | + |
| 29 | +In the example provided: |
| 30 | + |
| 31 | +- The hook is used to change the ownership of a volume to a non-root user (because volumes |
| 32 | +are created with root ownership by default). |
| 33 | +- After the container starts, the `chown` command changes the ownership of the `/data` directory to user `1001`. |
| 34 | + |
| 35 | +```yaml |
| 36 | +services: |
| 37 | + app: |
| 38 | + image: backend |
| 39 | + user: 1001 |
| 40 | + volumes: |
| 41 | + - data:/data |
| 42 | + post_start: |
| 43 | + - command: chown -R /data 1001:1001 |
| 44 | + user: root |
| 45 | + |
| 46 | +volumes: |
| 47 | + data: {} # a Docker volume is created with root ownership |
| 48 | +``` |
| 49 | +
|
| 50 | +### Pre-stop hooks |
| 51 | +
|
| 52 | +Pre-stop hooks are commands that run before the container is stopped by a specific |
| 53 | +command (like `docker compose down` or stopping it manually with `Ctrl+C`). |
| 54 | +These hooks won't run if the container stops by itself or gets killed suddenly. |
| 55 | + |
| 56 | +In the following example, before the container stops, the `./data_flush.sh` script is |
| 57 | +run to perform any necessary cleanup. |
| 58 | + |
| 59 | +```yaml |
| 60 | +services: |
| 61 | + app: |
| 62 | + image: backend |
| 63 | + pre_stop: |
| 64 | + - command: ./data_flush.sh |
| 65 | +``` |
0 commit comments