Skip to content

Docker

build_service(context, service)

Build service image.

Source code in saritasa_invocations/docker.py
10
11
12
13
14
15
@invoke.task
def build_service(context: invoke.Context, service: str) -> None:
    """Build service image."""
    printing.print_success(f"Building {service}")
    compose_cmd = _config.Config.from_context(context).docker.compose_cmd
    context.run(f"{compose_cmd} build {service}")

buildpack(context, env='development', builder='', builder_env='', runner='', tag='', clear_cache=False)

Build app image using buildpacks.

Source code in saritasa_invocations/docker.py
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
@invoke.task
def buildpack(
    context: invoke.Context,
    env: str = "development",
    builder: str = "",
    builder_env: str = "",
    runner: str = "",
    tag: str = "",
    clear_cache: bool = False,
) -> None:
    """Build app image using buildpacks."""
    config = _config.Config.from_context(context)
    # Builder needs requirements.txt
    if pathlib.Path(config.docker.buildpack_requirements_path).exists():
        shutil.copy(
            f"{config.docker.buildpack_requirements_path}/{env}.txt",
            "requirements.txt",
        )
    builder = builder or config.docker.buildpack_builder
    runner = runner or config.docker.buildpack_runner
    tag = tag or config.docker.build_image_tag
    cmd = f"pack build --builder={builder} --run-image={runner} {tag}"
    if clear_cache:
        cmd += " --clear-cache"
    if builder_env:
        cmd += f" --env={builder_env}"
    context.run(cmd)
    if pathlib.Path(config.docker.buildpack_requirements_path).exists():
        pathlib.Path("requirements.txt").unlink()

clear(context)

Stop and remove all containers defined in docker-compose.

Also remove images.

Source code in saritasa_invocations/docker.py
236
237
238
239
240
241
242
243
244
245
246
@invoke.task
def clear(context: invoke.Context) -> None:
    """Stop and remove all containers defined in docker-compose.

    Also remove images.

    """
    printing.print_success("Clearing docker-compose")
    compose_cmd = _config.Config.from_context(context).docker.compose_cmd
    context.run(f"{compose_cmd} rm -f")
    context.run(f"{compose_cmd} down -v --rmi all --remove-orphans")

docker_compose_exec(context, service, command)

Run exec using docker-compose.

docker compose exec Run commands in already running container.

Used function so later it can be extended to use different docker-compose files.


context: Invoke context
service: Name of service to run command in
command: Command to run in service container
Source code in saritasa_invocations/docker.py
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
def docker_compose_exec(
    context: invoke.Context,
    service: str,
    command: str,
) -> None:
    """Run ``exec`` using docker-compose.

    docker compose exec <service> <command>
    Run commands in already running container.

    Used function so later it can be extended to use different docker-compose
    files.

    Args:
    ----
        context: Invoke context
        service: Name of service to run command in
        command: Command to run in service container

    """
    compose_cmd = _config.Config.from_context(context).docker.compose_cmd
    cmd = f"{compose_cmd} exec {service} {command}"
    context.run(cmd)

docker_compose_run(context, container, command, params='', watchers=(), env=None, **kwargs)

Run command using docker-compose.

docker compose run Start container and run command in it.

Used function so later it can be extended to use different docker-compose files.


context: Invoke context
params: Configuration params for docker compose
container: Name of container to start
command: Command to run in started container
watchers: Automated responders to command
env: environmental variables for run
kwargs: additional arguments for context.run
Source code in saritasa_invocations/docker.py
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
def docker_compose_run(
    context: invoke.Context,
    container: str,
    command: str,
    params: str = "",
    watchers: collections.abc.Sequence[invoke.StreamWatcher] = (),
    env: dict[str, str] | None = None,
    **kwargs,
) -> invoke.runners.Result | None:
    """Run ``command`` using docker-compose.

    docker compose run <params> <container> <command>
    Start container and run command in it.

    Used function so later it can be extended to use different docker-compose
    files.

    Args:
    ----
        context: Invoke context
        params: Configuration params for docker compose
        container: Name of container to start
        command: Command to run in started container
        watchers: Automated responders to command
        env: environmental variables for run
        kwargs: additional arguments for context.run

    """
    compose_cmd = _config.Config.from_context(context).docker.compose_cmd
    env_params = " ".join(
        f"--env {env_key}={value}" for env_key, value in (env or {}).items()
    )
    return context.run(
        command=(
            f"{compose_cmd} run {params} {env_params} {container} {command}"
        ),
        watchers=watchers,
        **kwargs,
    )

stop(context)

Stop main containers.

Source code in saritasa_invocations/docker.py
226
227
228
229
230
231
232
233
@invoke.task
def stop(context: invoke.Context) -> None:
    """Stop main containers."""
    config = _config.Config.from_context(context)
    stop_containers(
        context,
        containers=config.docker.main_containers,
    )

stop_all_containers(context)

Shortcut for stopping ALL running docker containers.

Source code in saritasa_invocations/docker.py
115
116
117
118
@invoke.task
def stop_all_containers(context: invoke.Context) -> None:
    """Shortcut for stopping ALL running docker containers."""
    context.run("docker stop $(docker ps -q)")

stop_containers(context, containers)

Stop containers.

Source code in saritasa_invocations/docker.py
185
186
187
188
189
190
191
192
def stop_containers(
    context: invoke.Context,
    containers: collections.abc.Sequence[str],
) -> None:
    """Stop containers."""
    printing.print_success(f"Stopping {' '.join(containers)} containers")
    compose_cmd = _config.Config.from_context(context).docker.compose_cmd
    context.run(f"{compose_cmd} stop {' '.join(containers)}")

up(context, quite_pull=False, quite_build=False, remove_orphans=True)

Bring up main containers and start them.

Source code in saritasa_invocations/docker.py
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
@invoke.task
def up(
    context: invoke.Context,
    quite_pull: bool = False,
    quite_build: bool = False,
    remove_orphans: bool = True,
) -> None:
    """Bring up main containers and start them."""
    config = _config.Config.from_context(context)
    if not any(
        pathlib.Path(compose_file).exists()
        for compose_file in (
            "compose.yaml",
            "compose.yml",
            "docker-compose.yaml",
            "docker-compose.yml",
        )
    ):
        return
    if not config.docker.main_containers:
        return
    up_containers(
        context,
        containers=config.docker.main_containers,
        detach=True,
        quite_pull=quite_pull,
        quite_build=quite_build,
        remove_orphans=remove_orphans,
    )

up_containers(context, containers, detach=True, stop_others=True, quite_pull=False, quite_build=False, remove_orphans=True)

Bring up containers and run them.

Add d kwarg to run them in background.


context: Invoke context
containers: Name of containers to start
detach: To run them in background
stop_others: Stop ALL other containers in case of errors during `up`.
    Usually this happens when containers from other project uses the
    same ports, for example, Postgres and redis.
quite_pull: Suppress the build output
quite_build: Pull without printing progress information
remove_orphans: Remove containers for services that are not in the
    Compose file

UnexpectedExit: when `up` command wasn't successful
Source code in saritasa_invocations/docker.py
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
def up_containers(
    context: invoke.Context,
    containers: collections.abc.Sequence[str],
    detach: bool = True,
    stop_others: bool = True,
    quite_pull: bool = False,
    quite_build: bool = False,
    remove_orphans: bool = True,
) -> None:
    """Bring up containers and run them.

    Add `d` kwarg to run them in background.

    Args:
    ----
        context: Invoke context
        containers: Name of containers to start
        detach: To run them in background
        stop_others: Stop ALL other containers in case of errors during `up`.
            Usually this happens when containers from other project uses the
            same ports, for example, Postgres and redis.
        quite_pull: Suppress the build output
        quite_build: Pull without printing progress information
        remove_orphans: Remove containers for services that are not in the
            Compose file

    Raises:
    ------
        UnexpectedExit: when `up` command wasn't successful

    """
    if containers:
        printing.print_success(f"Bring up {', '.join(containers)} containers")
    else:
        printing.print_success("Bring up all containers")
    containers_str = " ".join(containers)
    detach_str = "--detach" if detach else ""
    quite_pull_str = "--quiet-pull" if quite_pull else ""
    quite_build_str = "--quiet-build" if quite_build else ""
    remove_orphans_str = "--remove-orphans" if remove_orphans else ""
    compose_cmd = _config.Config.from_context(context).docker.compose_cmd
    up_cmd = " ".join(
        filter(
            None,
            (
                compose_cmd,
                "up",
                quite_pull_str,
                quite_build_str,
                remove_orphans_str,
                detach_str,
                containers_str,
            ),
        ),
    )
    try:
        context.run(up_cmd)
    except invoke.UnexpectedExit:
        if not stop_others:
            raise
        stop_all_containers(context)
        context.run(up_cmd)