# Reduce a Docker Image's Size for a Flask App

Yes. An agent measures your image, adds a .dockerignore, moves the install into a build stage on a pinned base, drops duplicate installs and opens a PR with sizes.

[Run this on Rush](https://cloud.getrush.ai/run/reduce-image-size/docker/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent clones the app into its own cloud sandbox and reads the `Dockerfile` line by line before building anything. In an app like miguelgrinberg/microblog it is sixteen lines, twelve of them instructions: `FROM python:slim` with no version in the tag, `COPY requirements.txt` and `pip install -r requirements.txt` with the default cache, then a second `RUN pip install gunicorn pymysql cryptography` even though `gunicorn==21.2.0` is already pinned in `requirements.txt`, `COPY` of `app`, `migrations`, `microblog.py`, `config.py` and `boot.sh`, `ENV FLASK_APP microblog.py`, a `RUN flask translate compile` that builds the `.mo` file for the Spanish translation under `app/translations/es/`, `EXPOSE 5000` and `ENTRYPOINT ["./boot.sh"]`. `boot.sh` loops on `flask db upgrade` until it succeeds and then `exec`s `gunicorn -b :5000` with access and error logs on stdout. There is no `.dockerignore`, so the build context carries `.git`, any local `venv`, `app.db` and `microblog.log*`, the exact things `.gitignore` lists, plus `deployment/`, `Vagrantfile` and `tests.py`.

The sandbox has no Docker, so the agent installs it with `sudo apt-get install -y docker.io`, starts `dockerd`, and builds the image as it is to get a baseline from `docker image ls` and `docker history`, which shows which layer carries the weight. `requirements.txt` has pins the running app needs, `Flask==3.0.0`, `SQLAlchemy==2.0.23`, `psycopg2-binary==2.9.9`, `elasticsearch==8.11.0`, `redis==5.0.1` and `rq==1.15.1`, and pins the app does not import at runtime, `httpie==3.2.2` and its `rich` and `Pygments`, and `aiosmtpd==1.4.4.post2`, the local mail server from the tutorial. The agent does not remove those from `requirements.txt`, because the file is also the development environment; it lists them in the pull request as a candidate `requirements-dev.txt` split for the maintainer to decide.

The rewrite keeps the behaviour and changes the layers. A build stage on a pinned `python:<minor>-slim` tag, chosen to match the interpreter the maintainer runs rather than invented, creates a virtualenv at `/opt/venv` and installs `requirements.txt` with `--no-cache-dir`; the duplicate `gunicorn` install goes, and `pymysql` and `cryptography`, which are not in `requirements.txt` but are needed for a MySQL `DATABASE_URL`, move into it with exact pins so one file states what the image contains. The final stage copies `/opt/venv` and the application files, keeps `flask translate compile` so the `.mo` file is in the image, keeps `boot.sh` as the entrypoint and `5000` as the port. A `.dockerignore` excludes `.git`, `venv`, `app.db`, `*.log*`, `__pycache__`, `deployment`, `Vagrantfile`, `tests.py` and `*.mo`, the last so the compiled translation is always built fresh.

To prove nothing broke, the agent builds the new image, runs it with the default SQLite configuration from `config.py`, waits for `boot.sh` to finish `flask db upgrade` on the nine migrations under `migrations/versions/`, and requests `/` to see the redirect to the login page. It runs `python tests.py` on the host side to show the application code is untouched, then puts the before and after sizes from `docker image ls`, the layer breakdown and the request output in the pull request. Running as a non-root user and a `HEALTHCHECK` are named as the next two changes and left out of this one.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Reduce the size of this Flask app's Docker image without changing how it runs. Read the Dockerfile, boot.sh, requirements.txt, config.py and .gitignore first. The sandbox has no Docker: install docker.io, start dockerd, build the current image and record its size and layer history as the baseline. Then add a .dockerignore for the build context, pin the base image tag to a specific Python minor on slim, move the pip install into a build stage that installs into a virtualenv with --no-cache-dir and copy the virtualenv into the final stage, remove any package installed twice, and pin any package the old Dockerfile installed outside requirements.txt. Keep the translation compile step, the entrypoint and the port. Build the new image, run it with the default SQLite config, confirm the migrations apply and the index page answers, and run the unit tests. Open a pull request with the before and after sizes and the layer breakdown.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request that rewrites the `Dockerfile` as two stages, adds a `.dockerignore`, adds two exact pins to `requirements.txt` for the packages the old image installed by hand, and changes nothing under `app/`. The description shows the baseline and the new size from `docker image ls`, the layer breakdown from `docker history`, and the log of the container starting, applying the migrations and answering the index request.

The run's record keeps the Docker install, both builds, the container run and the `python tests.py` run, so a reviewer can see the number that was measured rather than estimated and that the entrypoint behaves as before. The `Procfile`, the `deployment/` configs for nginx and supervisor, and `boot.sh` are untouched.

Before merging, a reviewer picks the Python minor for the pinned tag if the agent's choice is not the one production runs, decides whether to split the development-only packages into their own requirements file, and schedules the non-root user and health check as the follow-up the description names.

## Run it on every Dockerfile change

Image size creeps back one pull request at a time. An automation with a `github` trigger on `pull_request.opened` and `pull_request.synchronize` starts one run per pull request; the agent checks out the branch, and when the diff does not touch the `Dockerfile`, `.dockerignore` or `requirements.txt`, ends with a one-line note. Only work by an owner, member or collaborator fires the trigger; pull requests from forks never do.

When the diff does touch them, the run installs Docker, builds the image from the base branch and from the pull request branch, and posts one review with the two sizes and the layers that grew, citing the `Dockerfile` line responsible. It pushes no commits; the author decides whether the growth is worth it, with the measurement in the run's record.

## Why run it on Rush?

Image size is a measurement, and the only honest way to report it is to build the image before and after in the same environment and read `docker image ls`. The agent does that in its own sandbox, installing Docker because the sandbox does not ship it, and keeps both builds and the container run in the record, so the pull request's numbers come from commands anyone can scroll to rather than from a guess about what a slim base saves.

The same request runs across every service an organisation builds images for, each in its own sandbox with its own baseline, and returns one pull request per repository with that repository's own before and after. The services that are already lean come back with a `.dockerignore` and a pinned tag; the ones that install a package twice or ship their `.git` directory come back with the layer that proves it.

## Frequently asked questions

### Will the app still apply migrations on start?

Yes. `boot.sh` is copied unchanged and stays the entrypoint, so the loop on `flask db upgrade` and the `exec gunicorn -b :5000` are exactly as before. The run shows the container applying the nine migrations against the default SQLite database before answering.

### Why not remove httpie and aiosmtpd from the image?

They are pinned in `requirements.txt`, which is also the development environment, so removing them changes the tutorial's workflow. The agent names them in the pull request as a candidate `requirements-dev.txt` split and leaves that decision to the maintainer.

### Which Python version does the pinned tag use?

The repository does not state one, so the agent chooses a current minor that satisfies the pinned packages, says so in the description, and asks the reviewer to confirm it matches production. Pinning to any specific minor is the point: `python:slim` today can be a different interpreter tomorrow.

### Does the agent need Docker Compose?

No. The app runs with SQLite and no Redis or Elasticsearch for the check the agent makes, since `config.py` defaults `SQLALCHEMY_DATABASE_URI` to a local `app.db` and `ELASTICSEARCH_URL` to unset. A full stack with Postgres and Redis is a separate exercise.

## More Docker jobs

- [Upgrade the Base Images in Your Dockerfiles Every Week](https://getrush.ai/run/upgrade-base-images/docker/)
- [Write Container Structure Tests for Docker Images](https://getrush.ai/run/write-container-structure-tests/docker/)
- [Add a Docker Bake File to Build Every Image in a Repository](https://getrush.ai/run/add-docker-bake/docker/)

## More jobs like this: Hand off a long task

- [Make Turborepo CI Check Only the Packages a Pull Request Changed](https://getrush.ai/run/run-ci-on-changed-packages/turborepo/)
- [Squash Alembic Migrations into One](https://getrush.ai/run/squash-migrations/alembic/)
- [Translate a Nuxt App Into Another Language](https://getrush.ai/run/translate-app-strings/nuxt/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
