boliveira
Welcome to my Social Blog
3y ago
Execute commands in a Docker DB container with Testcontainers
boliveira

Sometimes, it can be useful to execute specific commands against a running Docker container, especially in test contexts.
Once a container is running, it can be useful to, for example, execute a certain SQL script to populate a DB container with test data.

By leveraging this capability, you can enrich your containers at runtime with crafted data to cater to any test scenarios you might think of.

In fact, TestContainers makes this task very easy which is one extra reason why leveraging it to its full potential is a good idea. Let's see how:

Define a specific script to run from within a DB container

Let's say we have a script, in our machine, dummy.sql

containing some dummy data to populate a table.

What we want to do is to execute this SQL script against the running docker container database instance. For this, we can use the exec command from docker.

Using the exec command from Docker

We can use the "vanilla" docker CLI utility to load this file into the container by calling the command directly, in a fashion similar to:

docker cp ./dummy.sql <container_id>:/

docker exec <container_id> /bin/sh -c 'mysql -u root -ppassword </dummy.sql'

Here, we first copy the file into the container and then run the exec command against the running container.

Doing it via Testcontainers

The approach above can be replicated in any language that supports Testcontainers and relying on the execInContainer method supported by the library.

This command essentially mimics executing the docker exec but via an API specific to Testcontainers that interprets the output of the command as UTF-8.

If our running container is called testContainer, here's what executing a command in Docker via Testcontainers would look like:

testContainer.execInContainer("/bin/sh", "-c","mysql -u root -ppassword </dummy.sql");

Like this, we see how we can leverage the Testcontainers library to execute commands in a running container programmatically!

0

Atomic Essay

Comments

What will you write today?

Write, publish, get feedback, and become a better writer.

Trusted by 75,000+ writers