Passing Beanstalk software environmental variables to a Docker container


So, been trying out Docker in Amazon Beanstalk for a while now. It’s pretty neat, and makes it easier to install what you really want.
Setting environmental variables in Beanstalk is very helpful when using the same source repository for different environments. Let’s say you have a test, staging and production application set up in Beanstalk. How would you easily set different PHP settings inside the Docker container for each environment?
First of all, set the same variable names in all environments, but different, let say PHP-FPM pool settings.
In test environment, you would rather not need to run the same instance type as in production. For production you would also like to push everything you can out of the machine. You can’t do that with the same settings for all applications.
Set up the environments, and inside the Docker container you must set a ENTRYPOINT, to the Bash script.

[sourcecode language=”bash”]
#!/bin/bash
#
# entrypoint.sh
# Will setup environment for docker container.
#
# Created: 2015-01-23 09:09 kim@myrveln.se
# Changed: 2015-02-05 17:22 kim@myrveln.se
#

set -e

# Set some script paths
WWW="/etc/php5/fpm/pool.d/www.conf"

# —————————————— #
#
# We will pass system variables to
# PHP-FPM config. Environment variables
# set in Beanstalk will be automatically
# passed to the Docker container, and
# will be available here.
#

# Make magic according to system variables
# set in this Amazon Beanstalk environment.
ENVS=`printenv`

for ENV in ${ENVS}
do
IFS== read NAME VALUE <<< "${ENV}"
if [[ ! -z "${VALUE}" ]]; then
if [[ ! ${NAME} == "HOME" ]] \
&& [[ ! ${NAME} == "HOSTNAME" ]] \
&& [[ ! ${NAME} == "PWD" ]] \
&& [[ ! ${NAME} == "PATH" ]]; then
echo "env[${NAME}] = \"${VALUE}\"" | tee -a ${WWW}
fi
fi
done

exec "$@"
[/sourcecode]

This script will print all system variables that exists in the Docker container. You might find other variables you don’t want to include in the PHP variables. Strip them by adding more && [[ ! ${NAME}… lines.

Then in your Dockerfile you need to add the script, and the ENTRYPOINT line.
ADD /local/path/to/entrypoint.sh /scripts
ENTRYPOINT ["/scripts/entrypoint.sh"]