Docker Compose helper script
How to make a helper script to run docker compose commands

Make a new file at the root folder called dc without extension.

Content example. Modify for your needs.

 1#!/bin/bash
 2trap "exit" 0
 3DC="docker compose" # add  `-f docker/compose.yml` if it's in another folder
 4
 5if [ $# -eq 0 ]; then
 6    $DC ps -a
 7    
 8elif [ $1 == "up" ]; then
 9    $DC up -d
10    
11elif [ $1 == "php" ]; then
12    if [ $# -gt 1 ]; then
13        $DC exec php su app -c "${*:2}"
14    else
15        $DC exec php su app
16    fi
17    
18elif [ $1 == "c" ]; then
19    $DC exec php su app -c "composer ${*:2}"
20    
21elif [ $1 == "ci" ]; then
22    $DC exec php su app -c 'composer install'
23    
24elif [ $1 == "recreate" ]; then
25    $DC up -d --force-recreate ${*:2}
26    
27elif [ $1 == "build" ]; then
28    $DC up -d --force-recreate --build ${*:2}
29    
30else
31    $DC $*
32fi

Give execute permission with chmod +x ./dc

And now you can run:

  • ./dc - to show all containers with status
  • ./dc up - to start in detached mode
  • ./dc ci - to run composer install in the php container as user app
  • ./dc c require spatie/image - to run any composer command inside php container
  • ./dc php - interactive exec inside php container
  • ./dc php ls -alh - run any command inside php container
  • ./dc recreate - applies any modifications to docker-compose.yml
  • ./dc recreate php - applies modifications to compose, only for php container
  • ./dc build - if you have a custom dockerfile, does run dc up with a fresh build.
  • ./dc logs -n 10 -f php - any other docker-compose command works as expected.

Last modified on 2024-11-18

RO: Docker Compose script scurtaturi