javadockerdocker-apispotify-docker-client

Creating a mysql docker container setting env variables


I am using the spotify-docker-client to create and start a mysql container for testing. It works perfect, but I am having a hard time trying to find how to set certain values to connect to the database like MYSQL_ROOT_PASSWORD, MYSQL_DATABASE, MYSQL_USER, and MYSQL_PASSWORD. This is my code:

final ContainerConfig containerConfig = ContainerConfig.builder()
        .hostConfig(hostConfig)
        .image(image)
        .env("MYSQL_ROOT_PASSWORD","testrootpwd","MYSQL_DATABASE", "test", "MYSQL_USER", "test", "MYSQL_PASSWORD", "test")
        .build();

LOG.debug("Creating container for image: {}", image);
final ContainerCreation creation = this.docker.createContainer(containerConfig);

I am assuming that .env call is to set environment variables. And according to the mysql container documentation, setting those env variables is the way to do it:

https://hub.docker.com/_/mysql

But still, I can't connect to the container, I connected to bash and I see that those env variables are not set.

Does anyone know how to do it?

I could create a dockerfile and create my own image, but I don't want to do that, I want to do it with the spotify client.


Solution

  • This client uses docker API, so if the client is lacking documentation you can always check the original API. Check the CREATE A CONTAINER section in Docker Engine API.

    You can see that there is a JSON request example with env field:

    "Env": [
               "FOO=bar",
               "BAZ=quux"
    ],
    

    So my guess is that you can do just that in your Java code:

    final ContainerConfig containerConfig = ContainerConfig.builder()
        .hostConfig(hostConfig)
        .image(image)
        .env("MYSQL_ROOT_PASSWORD=testrootpwd", "MYSQL_DATABASE=test", ...)
        .build();
    

    P.S. Also please note what the documentation says regarding this param:

    A list of environment variables to set inside the container in the form ["VAR=value", ...]. A variable without = is removed from the environment, rather than to have an empty value.

    Might help you avoiding bugs later.