Skip
Arish's avatar

14. CMD and ENTRYPOINT


CMD - Default Command

dockerfile
1# Exec form (preferred)
2CMD ["rails", "server", "-b", "0.0.0.0"]
3
4# Shell form
5CMD rails server -b 0.0.0.0

Can be overridden:

bash
1docker run myapp rails console

ENTRYPOINT - Fixed Command

dockerfile
1ENTRYPOINT ["rails"]
2CMD ["server"]
bash
1docker run myapp          # rails server
2docker run myapp console  # rails console

Common Pattern

dockerfile
1# entrypoint.sh
2COPY entrypoint.sh /usr/bin/
3RUN chmod +x /usr/bin/entrypoint.sh
4ENTRYPOINT ["entrypoint.sh"]
5CMD ["rails", "server"]
bash
1#!/bin/bash
2# entrypoint.sh
3set -e
4
5# Remove stale pid
6rm -f /app/tmp/pids/server.pid
7
8# Run migrations
9bundle exec rails db:migrate
10
11# Execute CMD
12exec "$@"

Shell vs Exec Form

dockerfile
1# Shell form - runs in /bin/sh -c
2CMD rails server
3
4# Exec form - runs directly
5CMD ["rails", "server"]

Exec form is preferred for proper signal handling.