Elastic Beanstalk: Deploy-time commands inside Docker

0 votes

I have a Django service running inside Docker that I deploy to AWS Elastic Beanstalk.

I would like to run my database migrations at deploy-time

If I were deploying to EB as "a Python project", I could have the following in my .ebextensions:

$ cat .ebextensions/01run.config 
container_commands:
    01migrate:
        command: "python manage.py migrate --noinput"
        leader_only: true

However, container_commands are for the EC2 instances - and it's inside the Docker container that I have my code etc.

Things I've already looked at

  • I can't just add it to my Dockerfile, because applying migrations is all about operating on the attached RDS instance (supplied by the environment) - not really "part of building the Docker image"

  • There doesn't seem to be anything useful I can add to Dockerrun.aws.json

Ideas very much welcomed please!

Nov 14, 2018 in AWS by Jino
• 5,560 points
346 views

1 answer to this question.

0 votes

You could add a post deploy script in your .ebextensions like so:

files:
  "/opt/elasticbeanstalk/hooks/appdeploy/post/10_migrate.sh":
    mode: "000755"
    owner: root
    group: root
    content: |
      #!/usr/bin/env bash
      if [ -f /tmp/leader_only ]; then
        echo "Running Migrations"
        container_id=`docker ps -q --no-trunc --filter label="com.amazonaws.ecs.container-name=MY_CONTAINER_NAME" | head -n 1`
        docker inspect $container_id
        docker exec $container_id /entrypoint.sh python manage.py migrate --noinput
      fi
  "/opt/elasticbeanstalk/hooks/appdeploy/post/90_rm_leader_only.sh":
    mode: "000755"
    owner: root
    group: root
    content: |
      #!/usr/bin/env bash
      if [ -f /tmp/leader_only ]; then
        echo "Deleting leader_only file"
        rm /tmp/leader_only
      fi
container_commands:
  01_touch_the_leader:
    command: |
      #!/usr/bin/env bash
      touch /tmp/leader_only
    leader_only: true

I have included the leader only bit in case you might be using a load balanced environment, it won't run migrations on multiple servers at once. This can also be used for the collectstatic command.

answered Nov 14, 2018 by Theodor
• 740 points

Related Questions In AWS

0 votes
1 answer

What is difference between commands and container commands in Elastic Beanstalk?

The major difference between these two pieces ...READ MORE

answered Sep 12, 2018 in AWS by Archana
• 4,090 points
201 views
0 votes
1 answer

Deploy multiple platforms to Elastic Beanstalk

Solve by using .ebextentions to run pre-install commands in ...READ MORE

answered Nov 28, 2018 in AWS by Archana
• 5,560 points
77 views
0 votes
1 answer
0 votes
1 answer

Deploy Docker Containers from Docker Cloud

To solve this problem, I followed advice ...READ MORE

answered Sep 3, 2018 in AWS by Priyaj
• 56,920 points
226 views