I am running docker-container on Amazon EC2. Currently I have added AWS Credentials to Dockerfile. Could you please let me know the best way to do this?
A lot has changed in Docker since this question was asked, so here's an attempt at an updated answer.
First, specifically with AWS credentials on containers already running inside of the cloud, using IAM roles as Vor suggests is a really good option. If you can do that, then add one more plus one to his answer and skip the rest of this.
Once you start running things outside of the cloud, or have a different type of secret, there are two key places that I recommend against storing secrets:
Environment variables: when these are defined on a container, every process inside the container has access to them, they are visible via /proc, apps may dump their environment to stdout where it gets stored in the logs, and most importantly, they appear in clear text when you inspect the container.
In the image itself: images often get pushed to registries where many users have pull access, sometimes without any credentials required to pull the image. Even if you delete the secret from one layer, the image can be disassembled with common Linux utilities like tar and the secret can be found from the step where it was first added to the image.
So what other options are there for secrets in Docker containers?
Option A: If you need this secret only during the build of your image, cannot use the secret before the build starts, and do not have access to BuildKit yet, then a multi-stage build is a best of the bad options. You would add the secret to the initial stages of the build, use it there, and then copy the output of that stage without the secret to your release stage, and only push that release stage to the registry servers. This secret is still in the image cache on the build server, so I tend to use this only as a last resort.
Option B: Also during build time, if you can use BuildKit which was released in 18.09, there are currently experimental features to allow the injection of secrets as a volume mount for a single RUN line. That mount does not get written to the image layers, so you can access the secret during build without worrying it will be pushed to a public registry server. The resulting Dockerfile looks like:
# syntax = docker/dockerfile:experimental
FROM python:3
RUN pip install awscli
RUN --mount=type=secret,id=aws,target=/root/.aws/credentials aws s3 cp s3://... ...
And you build it with a command in 18.09 or newer like:
DOCKER_BUILDKIT=1 docker build -t your_image --secret id=aws,src=$HOME/.aws/credentials .
Option C: At runtime on a single node, without Swarm Mode or other orchestration, you can mount the credentials as a read only volume. Access to this credential requires the same access that you would have outside of docker to the same credentials file, so it's no better or worse than the scenario without docker. Most importantly, the contents of this file should not be visible when you inspect the container, view the logs, or push the image to a registry server, since the volume is outside of that in every scenario. This does require that you copy your credentials on the docker host, separate from the deploy of the container. (Note, anyone with the ability to run containers on that host can view your credential since access to the docker API is root on the host and root can view the files of any user. If you don't trust users with root on the host, then don't give them docker API access.)
For a docker run, this looks like:
docker run -v $HOME/.aws/credentials:/home/app/.aws/credentials:ro your_image
Or for a compose file, you'd have:
version: '3'
services:
app:
image: your_image
volumes:
- $HOME/.aws/credentials:/home/app/.aws/credentials:ro
Option D: With orchestration tools like Swarm Mode and Kubernetes, we now have secrets support that's better than a volume. With Swarm Mode, the file is encrypted on the manager filesystem (though the decryption key is often there too, allowing the manager to be restarted without an admin entering a decrypt key). More importantly, the secret is only sent to the workers that need the secret (running a container with that secret), it is only stored in memory on the worker, never disk, and it is injected as a file into the container with a tmpfs mount. Users on the host outside of swarm cannot mount that secret directly into their own container, however, with open access to the docker API, they could extract the secret from a running container on the node, so again, limit who has this access to the API. From compose, this secret injection looks like:
version: '3.7'
secrets:
aws_creds:
external: true
services:
app:
image: your_image
secrets:
- source: aws_creds
target: /home/user/.aws/credentials
uid: '1000'
gid: '1000'
mode: 0700
You turn on swarm mode with docker swarm init for a single node, then follow the directions for adding additional nodes. You can create the secret externally with docker secret create aws_creds $HOME/.aws/credentials. And you deploy the compose file with docker stack deploy -c docker-compose.yml stack_name.
I often version my secrets using a script from: https://github.com/sudo-bmitch/docker-config-update
Option E: Other tools exist to manage secrets, and my favorite is Vault because it gives the ability to create time limited secrets that automatically expire. Every application then gets its own set of tokens to request secrets, and those tokens give them the ability to request those time limited secrets for as long as they can reach the vault server. That reduces the risk if a secret is ever taken out of your network since it will either not work or be quick to expire. The functionality specific to AWS for Vault is documented at https://www.vaultproject.io/docs/secrets/aws/index.html
The best way is to use IAM Role and do not deal with credentials at all. (see http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html )
Credentials could be retrieved from http://169.254.169.254..... Since this is a private ip address, it could be accessible only from EC2 instances.
All modern AWS client libraries "know" how to fetch, refresh and use credentials from there. So in most cases you don't even need to know about it. Just run ec2 with correct IAM role and you good to go.
As an option you can pass them at the runtime as environment variables ( i.e docker run -e AWS_ACCESS_KEY_ID=xyz -e AWS_SECRET_ACCESS_KEY=aaa myimage)
You can access these environment variables by running printenv at the terminal.
Yet another approach is to create temporary read-only volume in docker-compose.yaml. AWS CLI and SDK (like boto3 or AWS SDK for Java etc.) are looking for default profile in ~/.aws/credentials file.
If you want to use other profiles, you just need also to export AWS_PROFILE variable before running docker-compose command.
export AWS_PROFILE=some_other_profile_name
version: '3'
services:
service-name:
image: docker-image-name:latest
environment:
- AWS_PROFILE=${AWS_PROFILE}
volumes:
- ~/.aws/:/root/.aws:ro
In this example, I used root user on docker. If you are using other user, just change /root/.aws to user home directory.
:ro - stands for read-only docker volume
It is very helpful when you have multiple profiles in ~/.aws/credentials file and you are also using MFA. Also helpful when you want to locally test docker-container before deploying it on ECS on which you have IAM Roles, but locally you don't.
Another approach is to pass the keys from the host machine to the docker container. You may add the following lines to the docker-compose file.
services:
web:
build: .
environment:
- AWS_ACCESS_KEY_ID=${AWS_ACCESS_KEY_ID}
- AWS_SECRET_ACCESS_KEY=${AWS_SECRET_ACCESS_KEY}
- AWS_DEFAULT_REGION=${AWS_DEFAULT_REGION}
The following one-liner works for me even when my credentials are set up by aws-okta or saml2aws:
$ docker run -v$HOME/.aws:/root/.aws:ro \
-e AWS_ACCESS_KEY_ID \
-e AWS_CA_BUNDLE \
-e AWS_CLI_FILE_ENCODING \
-e AWS_CONFIG_FILE \
-e AWS_DEFAULT_OUTPUT \
-e AWS_DEFAULT_REGION \
-e AWS_PAGER \
-e AWS_PROFILE \
-e AWS_ROLE_SESSION_NAME \
-e AWS_SECRET_ACCESS_KEY \
-e AWS_SESSION_TOKEN \
-e AWS_SHARED_CREDENTIALS_FILE \
-e AWS_STS_REGIONAL_ENDPOINTS \
amazon/aws-cli s3 ls
Please note that for advanced use cases you might need to allow rw (read-write) permissions, so omit the ro (read-only) limitation when mounting the .aws volume in -v$HOME/.aws:/root/.aws:ro
Volume mounting is noted in this thread but as of docker-compose v3.2 + you can Bind Mount.
For example, if you have a file named .aws_creds in the root of your project:
In your service for the compose file do this for volumes:
volumes:
# normal volume mount, already shown in thread
- ./.aws_creds:/root/.aws/credentials
# way 2, note this requires docker-compose v 3.2+
- type: bind
source: .aws_creds # from local
target: /root/.aws/credentials # to the container location
Using this idea, you can publicly store your docker images on docker-hub because your aws credentials will not physically be in the image...to have them associated, you must have the correct directory structure locally where the container is started (i.e. pulling from Git)
You could create ~/aws_env_creds containing:
touch ~/aws_env_creds
chmod 777 ~/aws_env_creds
vi ~/aws_env_creds
Add these value (replace the key of yours):
AWS_ACCESS_KEY_ID=AK_FAKE_KEY_88RD3PNY
AWS_SECRET_ACCESS_KEY=BividQsWW_FAKE_KEY_MuB5VAAsQNJtSxQQyDY2C
Press "esc" to save the file.
Run and test the container:
my_service:
build: .
image: my_image
env_file:
- ~/aws_env_creds
If someone still face the same issue after following the instructions mentioned in accepted answer then make sure that you are not passing environment variables from two different sources. In my case I was passing environment variables to docker run via a file and as parameters which was causing the variables passed as parameters show no effect.
So the following command did not work for me:
docker run --env-file ./env.list -e AWS_ACCESS_KEY_ID=ABCD -e AWS_SECRET_ACCESS_KEY=PQRST IMAGE_NAME:v1.0.1
Moving the aws credentials into the mentioned env.list file helped.
for php apache docker the following command works
docker run --rm -d -p 80:80 --name my-apache-php-app -v "$PWD":/var/www/html -v ~/.aws:/.aws --env AWS_PROFILE=mfa php:7.2-apache
Based on some of previous answers, I built my own as follows.
My project structure:
├── Dockerfile
├── code
│ └── main.py
├── credentials
├── docker-compose.yml
└── requirements.txt
My docker-compose.yml file:
version: "3"
services:
app:
build:
context: .
volumes:
- ./credentials:/root/.aws/credentials
- ./code:/home/app
My Docker file:
FROM python:3.8-alpine
RUN pip3 --no-cache-dir install --upgrade awscli
RUN mkdir /app
WORKDIR /home/app
CMD python main.py
I am new to Docker and containers in general. I played around and got to a point, where I do not get any further. I searched through other questions but I couldn't see the right question (or understand) the answers. So I hope you can help me.
I do have two containers, running php:7.4-apache and mariadb. They are working fine and if I use a docker compose file, I can start everything well with docker-compose up -d.
Here the docker compose file (remember, this is my first file, so I have not that much knowledge about it):
version: '3.1'
services:
mariadb:
image: mariadb:latest
environment:
- MYSQL_DATABASE=mydb
- MYSQL_USER=myuser
- MYSQL_PASSWORD=secret
- MYSQL_ROOT_PASSWORD=docker
ports:
- "3306:3306"
volumes:
- ./database/storage
- ./database/src:/usr/src
restart: always
php:
image: php:7.4-apache
ports:
- 80:80
volumes:
- ./php/src:/var/www/html/
restart: always
My "project structure" looks like this:
If I start now the dev container, I can choose to use the docker-compose file. I did this, and the first thing I didn't understand is, that I have to choose between those two services (php/mariadb).
So I used php for a try. It starts running, and I can see the container with docker ps.
However, if I want to connect to the php-website via localhost:80 and see my "website", I do not get any connections.
I expected the same behavior like if I would use the docker-compose up. But this doesn't happen. Here is the devcontainer.json, it might help:
// If you want to run as a non-root user in the container, see .devcontainer/docker-compose.yml.
{
"name": "Existing Docker Compose (Extend)",
// Update the 'dockerComposeFile' list if you have more compose files or use different names.
// The .devcontainer/docker-compose.yml file contains any overrides you need/want to make.
"dockerComposeFile": [
"..\\Docker-compose.yml",
"docker-compose.yml"
],
// The 'service' property is the name of the service for the container that VS Code should
// use. Update this value and .devcontainer/docker-compose.yml to the real service name.
"service": "php",
// The optional 'workspaceFolder' property is the path VS Code should open by default when
// connected. This is typically a file mount in .devcontainer/docker-compose.yml
"workspaceFolder": "/workspace",
// Set *default* container specific settings.json values on container create.
"settings": {
"terminal.integrated.shell.linux": null
},
// Add the IDs of extensions you want installed when the container is created.
"extensions": [],
// Use 'forwardPorts' to make a list of ports inside the container available locally.
"forwardPorts": [80],
// Uncomment the next line if you want start specific services in your Docker Compose config.
// "runServices": [],
// Uncomment the next line if you want to keep your containers running after VS Code shuts down.
// "shutdownAction": "none",
// Uncomment the next line to run commands after the container is created - for example installing curl.
// "postCreateCommand": "apt-get update && apt-get install -y curl",
// Uncomment to connect as a non-root user if you've added one. See https://aka.ms/vscode-remote/containers/non-root.
// "remoteUser": "vscode"
}
As you can see, I tried forwarding the port 80, but this didn't work either. It is also confusing, that the docker-compose.yml within the .devcontainer folder is not the same yml as my original Docker-compose.yml.
I have no idea on what to do next. I hope, that I can use visual studio code for making simple php scripts within this container and later on, connect to the mariadb. Both mariadb and php should run in seperate containers. Well, at least that was my hope.
---Additional information---
To show what VisualStudio Code is showing me, here some screenshots:
I choose to open folder in container.
Then I choose the Docker-compose.yml (Which is working fine if I use docker-compose up).
As you can see, it is now asking me about which service I want to select. Which if funny, because I would like both service to run ... But in this scenario, it would be fine if I could change via VS-Code the php scripts.
Thanks for the help
-GreNait
I've created a Docker container with an Ubuntu base image. Setting the environment variables through a .env file. When running the container, I can see the variables being passed through using the shell terminal.
I want to able to get the env varibles in my wp-config. I am using getenv but it is not working..
Any suggestions..
Thanks
You can set the environment variable for your docker container in 2 ways
In docker run command use docker run -e VARIABLE=VALUE ...
In docker-compose file you can set in like:
environment:
- DEBUG=1
https://docs.docker.com/compose/environment-variables/#set-environment-variables-in-containers
You use .env file, so you certainly use docker-compose. If not use docker-compose, .env will not make effect. And the .env file must be placed in the directory where docker-compose is run from.
Whole solution could be something like:
.env
MY_VARIABLE=abc
docker-compose.yml
version: '3'
services:
my_service:
environment:
- MY_VARIABLE="${MY_VARIABLE}"
wp-config.php
echo getenv('MY_VARIABLE');
I guess you did not get env because you did not do - MY_VARIABLE="${MY_VARIABLE}" in docker-compose.yml, the value in .env will not be automatically act as an environment variable to container, you need to handle it in compose file. FYI.
Detail refers to offical guide
Both previous answers, I could already pass the env variables to my apache environment served by docker. I just needed to add Pass env_name to the .htaccess file for each env variable.
I could then get the values via the $SERVER['env_name'] within my php application..
I am using the image richarvey/nginx-php-fpm:latest (1.5.2) and I started a container based on this image and executed /bin/bash inside.
There I :
have installed composer
created a new symfony4 project using composer create-project symfony/website-skeleton my-project
have edited my-project/config/packages/dev/monolog.yaml to set :
monolog:
handlers:
main:
type: stream
path: 'php://stderr'
level: debug
channels: ["!event"]
got the IP of my docker image using docker inspect
and dump my container logs using docker logs -f <my container>
When I load http://<my container ip>/my-project/public, I don't see the symfony debug logs in my container logs output.
Note : I see the nginx logs.
One of my coworker found the solution and the docker image maintainer implemented it :
https://gitlab.com/ric_harvey/nginx-php-fpm/commit/51bbf4e04f61873dfeae69e943fcdf0a900f2589#8ad4b94617a62f898119a66a878f8035b8605d13
As php-fpm is run in nodaemonized mode, you need to set the --force-stderr flag which "Force output to stderr in nodaemonize even if stderr is not a TTY."
https://www.gsp.com/cgi-bin/man.cgi?section=8&topic=php-fpm
I am using docker container that runs codeigniter application and I have setted enviroment variable for base url in docker composer.yml like:
version: '3.4' services:
app:
image: WEBPORTAL_VERSION
ports:
- port_key:port_num
environment:
- BASE_URL=http://example.com
deploy:
mode: replicated
replicas: 1
placement:
constraints:
- node.role == manager
Now, I want to access the environment key i.e. base url in codeigniter application
I am using:
$_config['base_url']=getenv('BASE_URL');
where BASE_URL is key initialized in docker composer file above.
The problem here is getenv do not fetch from environment set in docker composer?
Finally! solved the problem, by default in php-fpm config file was taking
clear_env = yes
which is the default value, I changed it and updated as
clear_env=no