Skip to content
watch on youtubeThe notes below cover everything in the video. Find it in the playlist on our channel.Open the YouTube channel
Lesson 7 of 109 min video

Docker: From Your Laptop to Amazon ECR

Write a Dockerfile, build and run a container, push the image to a private Amazon ECR repository, and run it on EC2 with an IAM role.

Video chapters

  1. 00:00Intro
  2. 00:38Why containers took over
  3. 01:30Image, container, Dockerfile
  4. 02:31Step 1: Build and run locally
  5. 03:53Habits for good images
  6. 04:52Step 2: Create a private ECR repository
  7. 05:44Step 3: Push your image
  8. 06:43Step 4: Run it on EC2, with a role
  9. 07:56Where containers run on AWS
  10. 09:11Build once, run anywhere

Containers package an application with everything it needs, so it runs the same way on your laptop, a test server, and production. In this episode you build an image, store it in Amazon ECR, and run it on EC2, using an IAM role instead of keys.

What you need

  • Docker installed locally (Docker Desktop or Docker Engine)
  • AWS CLI from Episode 3
  • An EC2 instance (Episode 4)

Why containers took over

Why did containers take over the industry?

Because they're the same everywhere. A container holds your application together with its runtime and libraries, so if it runs on your laptop, it runs on the server.

They're lightweight. Unlike a virtual machine, a container shares the host's operating system kernel, so it starts in seconds and uses little memory.

They're repeatable. A Dockerfile is a recipe, and anyone can rebuild exactly the same image from it.

They're versioned. Each build gets a tag, like one point zero or one point one, and rolling back is just running the previous tag.

And they're cloud-native. AWS's container services, and Kubernetes everywhere, are built to run exactly these images. Learn containers once, and you can deploy almost anywhere.

Quick reference

  • Same everywhere: App + runtime + libraries, packaged together
  • Lightweight: Share the host's kernel. Start in seconds
  • Repeatable: One Dockerfile = one recipe anyone can rebuild
  • Versioned: hello-api:1.0, 1.1… roll back in one command
  • Cloud-native: ECS, EKS, Fargate and Lambda all run containers

Image, container, Dockerfile

Five words to know. An image is a read-only package, containing your app and everything it needs.

A container is a running instance of an image. One image can run as many containers as you like.

A Dockerfile is the recipe for building an image. Here's one for a small Python web API.

Read it top to bottom. Start from an official, slim Python image. Set the working folder. Copy the requirements file first, and install dependencies. Then copy the rest of the code. Switch to a non-root user. Document the port, and set the command that starts the app. Each line creates a layer, and Docker reuses unchanged layers, which makes rebuilds fast.

A registry is where images are stored and shared. Docker Hub is public. Amazon E C R is AWS's private registry, and we'll use it today.

And a tag is a version label, like hello dash api, colon, one point zero.

Quick reference

  • Image: A read-only package: app + everything it needs
  • Container: A running instance of an image
  • Dockerfile: The recipe that builds the image
  • Registry: Where images are stored: Docker Hub, ECR
  • Tag: A version label: hello-api:1.0

Dockerfile

FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir \
    -r requirements.txt
COPY . .
USER nobody
EXPOSE 8000
CMD ["python", "app.py"]

Step 1 · Build and run locally

Step one: build and run it locally. In the project folder, docker build creates the image. Dash t gives it a name and tag, and the dot means use this folder.

docker run starts a container from it. Dash d runs it in the background, dash p connects port eight thousand on your computer to port eight thousand inside the container, and dash dash name gives the container a friendly name.

curl it, and the API answers.

docker ps lists running containers.

docker logs, with dash f, follows the app's output, just like tail dash f on a log file.

And docker stop, then docker rm, stops and removes the container. The image stays, ready to run again.

The most common beginner mistake is the port mapping. It's host port, colon, container port. If the app inside listens on a different port than the one you mapped, you'll get connection refused.

Another one that catches people: inside a container, the app must listen on zero dot zero dot zero dot zero, not on localhost. Localhost inside a container means only the container itself, so traffic from outside never reaches the app. Most frameworks default to localhost in development mode, so check this setting first when a container runs but doesn't answer.

Quick reference

docker build -t hello-api:1.0 .
docker run -d -p 8000:8000 --name hello hello-api:1.0
curl localhost:8000          # {"message": "hello"}
docker ps                    # running containers
docker logs -f hello         # the app's output
docker stop hello && docker rm hello
Tip: -p 8000:8000 = host port : container port. Mismatch = “connection refused”.

Habits for good images

Five habits that make your images smaller, faster and safer.

Use slim base images. Smaller images build faster, download faster, and contain fewer packages with security problems.

Add a dot dockerignore file, listing things like the git folder, dot env files, and node modules. They don't belong in the image, and secrets in particular must never end up there.

Order your Dockerfile for caching. Install dependencies before copying your code. Then changing one line of code doesn't reinstall every library.

Run as a non-root user. If someone breaks into your app, they don't get root inside the container.

And never bake secrets into an image. Anyone who can pull the image can read every file in it. Pass configuration in when the container starts, with environment variables, or better, from a secret store, like we discussed in the RDS episode.

Quick reference

  • Slim base images: python:3.12-slim, not the full image
  • .dockerignore: Keep .git, .env, node_modules out of the image
  • Order for caching: Dependencies first, code last
  • Non-root user: USER nobody (or a dedicated user)
  • No secrets inside: Pass config at runtime, never bake it in

Step 2 · Create a private ECR repository

Step two: a private registry. Open the E C R console, elastic container registry, and create a repository.

Keep it private, and name it hello dash api.

Turn on image scanning. E C R then checks your images for known vulnerabilities in their packages.

Turn on tag immutability. Once version one point zero is pushed, nobody can overwrite it with different contents. When you say one point zero, it always means the same thing.

And add a lifecycle policy that keeps, say, the last ten images. Old images are deleted automatically, so storage costs stay small.

Copy the repository U R I. It contains your account number, region, and repository name. Every image you push will be addressed by this U R I, plus a tag.

Quick reference

  1. ECR console → Create repository
  2. Visibility: Private · Name: hello-api
  3. Image scanning: on (find known vulnerabilities)
  4. Tag immutability: on (1.0 can't be overwritten)
  5. Lifecycle policy: keep the last 10 images

repository URI

123456789012.dkr.ecr.<region>
  .amazonaws.com/hello-api

image:  <URI>:1.0

Step 3 · Push your image

Step three: push. To keep commands short, save the registry address in a variable.

Docker needs to log in to E C R. The AWS CLI gets a temporary password,

and pipes it straight into docker login. The password never appears on screen or in your shell history.

Tag your local image with the full repository address and version.

And push it. Refresh the E C R console, and your image is there, with its tag, size, and scan results.

One gotcha. If you build on an Apple Silicon Mac, your image is built for A R M by default. If your servers use regular x86 processors, add dash dash platform linux slash amd64 to the build command, or choose A R M based instances, like t4g.

And the login lasts twelve hours. If push says no basic auth credentials, just run the login command again.

Quick reference

export REPO=123456789012.dkr.ecr.<region>.amazonaws.com
aws ecr get-login-password --region <region> \
    | docker login --username AWS --password-stdin $REPO
docker tag hello-api:1.0 $REPO/hello-api:1.0
docker push $REPO/hello-api:1.0
Tip: The login token lasts 12 hours. “no basic auth credentials” = log in again.

Step 4 · Run it on EC2, with a role

Step four: run the same image on EC2. And this time, we'll do it properly, with an I A M role, not access keys.

In I A M, create a role for the EC2 service, and attach the AWS managed policy that gives read-only access to E C R. The server can pull images, but it can't push or delete anything. Least privilege again.

In the EC2 console, select your instance, and under actions, security, choose modify I A M role, and attach the new role.

Now SSH in, install Docker, and run the same login command. Notice it works without aws configure. The CLI automatically gets temporary credentials from the role, and they rotate on their own. There's no secret stored anywhere on this server.

Then run the container, mapping port eighty on the server to port eight thousand in the container, with a restart policy so it comes back after a reboot.

Open the server's public IP, and you'll see the same API you ran on your laptop. Same image, same behavior, a different machine. That's the promise of containers, delivered.

Quick reference

  1. IAM → Roles → Create role for EC2
  2. Policy: AmazonEC2ContainerRegistryReadOnly
  3. EC2 → Actions → Security → Modify IAM role
  4. On the server: install Docker, log in, pull, run
  5. Security group: port 80 open → open the public IP

on web-1 · no access keys

$ aws ecr get-login-password \
    --region <region> | docker login \
    --username AWS --password-stdin $REPO
$ docker run -d --restart unless-stopped \
    -p 80:8000 $REPO/hello-api:1.0

Where containers run on AWS

Running Docker on a single EC2 server is a great way to learn. Here's where containers run in real AWS projects.

EC2 with Docker, what we did today. You have full control, and full responsibility for the server.

E C S on Fargate. You describe the container, the C P U and memory, and how many copies you want, and AWS runs them for you, with no servers to patch. For many teams, this is the default choice.

E K S is managed Kubernetes. It's very powerful, and very popular in larger companies, but it's also much more complex. Learn it after you're comfortable with the basics.

And Lambda can run container images too, as serverless functions that start on demand.

My advice: learn with EC2, like today, then move to E C S on Fargate for most production work. Kubernetes can come later, when you have a reason for it.

Whichever you choose, the skills from today carry over completely. The Dockerfile, the image, the registry, the tags, and the I A M role pattern are exactly the same. Only the thing that starts the containers changes.

Quick reference

  • EC2 + Docker: What we did today. Full control, you manage it
  • ECS on Fargate: AWS runs containers for you. No servers to patch
  • EKS: Managed Kubernetes. Powerful, more complex
  • Lambda: Container images as serverless functions
  • Start simple: EC2 to learn, ECS Fargate for most production

Build once, run anywhere

Let's recap. You wrote a Dockerfile, built an image, and ran it locally. You created a private, scanned E C R repository, and pushed a versioned image. And you pulled and ran it on EC2, using an I A M role instead of access keys.

To clean up, stop the container, or terminate the instance if you're finished with it, and delete images you no longer need. E C R storage is cheap, but it's not free.

So far, we've created everything by clicking in the console. In the next episode, that changes. We'll describe infrastructure as code with Terraform, so you can create, change and delete whole environments with a single command. The notes, with every command from today, are linked in the description.

Quick reference

Dockerfile → Image → Amazon ECR → EC2 + role

Clean up: stop the container, detach the role, delete old images

Practice

  1. Add a .dockerignore and compare image sizes before and after.
  2. Push version 1.1 of the image and roll back to 1.0 on EC2.
  3. Add an ECR lifecycle policy that keeps only the last 5 images.

Next episode

Episode 8: Terraform, describing your infrastructure as code.

Key takeaways

  • An image is the package, a container is a running image, and a Dockerfile is the recipe
  • Use slim base images, a .dockerignore, a non-root user and no secrets in the image
  • Push tagged images to a private ECR repository after logging in with the AWS CLI
  • Give EC2 an IAM role to pull images instead of storing access keys on it