Running Docker container within Elastic Beanstalk is a good way to quickly setup a Docker container environment in AWS. In my experience it is an easier setup than using ECS.
However, once you’re up and running, it can be a little tricky to figure out how to login to your container if you need to debug. In my case, once in a while, I need to be able to run rails console on production or QA to debug issues.
Elastic Beanstalk relies on a few scripts and files to maintain the state of the environment. Here is how you can access your Dockerized application in Elastic Beanstalk
Step 1: Not much you can do without super user access
eb ssh [environment-name-in-elastic-beanstalk]
sudo suStep 2: Generate environmental variables
eval $(cat /opt/elasticbeanstalk/hooks/appdeploy/enact/00run.sh |grep "EB_SUPPORT_FILES=")
$EB_SUPPORT_FILES/generate_env > /tmp/envStep 3: Determine id of the currently running docker image
IMAGE_ID=`cat /etc/elasticbeanstalk/.aws_beanstalk.current-image-id`Step 4: Run command with you environment
docker run -it --env-file /tmp/env $IMAGE_ID bundle exec rails cor if just login int your virtual machine’s shell
docker run -it --env-file /tmp/env $IMAGE_ID /bin/bashStep 5: Clean up
If you don’t close your connection cleanly, there is a chance that you can leave extra Docker containers running which will eat up unnecessary resources on your machine. So don’t forget to shutdown unnecessary docker containers
CONTAINER_ID=`cat /etc/elasticbeanstalk/.aws_beanstalk.current-container-id`# stop all running containers except the current one
docker ps -qa --no-trunc |grep -v $CONTAINER_ID |xargs docker stop
