How to Run a Command After Building a Docker Container?

April 20, 2025 3 answers
Asked by LemonVerbena
I'm new to Docker Compose and I'm trying to figure out how to run a command after my container is built. Here's the configuration I'm using for a service called 'sabnzbd': ```yaml services: sabnzbd: image: lscr.io/linuxserver/sabnzbd:latest container_name: sabnzbd environment: - PUID=1003 - PGID=1003 - TZ=America/New_York volumes: - /docker/sabnzbd:/config - /downloads:/downloads ports: - 8080:8080 command: bash -c "apk add --no-cache ffmpeg" restart: unless-stopped ``` The issue is that the container keeps rebooting, so I must be doing something wrong with my command. Any advice? Thanks!

Answers

percussion mallet
You might consider using a Dockerfile instead of trying to run commands directly in your Compose file. In the Dockerfile, you can include all your necessary build steps, including package installations. This keeps your container behavior consistent and avoids restart issues. Let me know if you need examples!
Reply to this answer
crop_16by9
The reason your container keeps restarting is that your command overrides the container's default startup command. When you specify `command: bash -c "apk add --no-cache ffmpeg"`, it only runs this command. Once it finishes, the container exits, which makes Docker restart it (because of the `restart: unless-stopped` policy). You might want to rethink how you handle commands in the Dockerfile or use a separate script that runs after your service starts.
Reply to this answer
winterizing
If you're using a LinuxServer image, you can leverage their mods to install packages after the container is created. Check out their universal package install mod on GitHub. You can set it up like this: ```yaml services: sabnzbd: image: lscr.io/linuxserver/sabnzbd:latest container_name: sabnzbd environment: - PUID=1003 - PGID=1003 - TZ=America/New_York - DOCKER_MODS=linuxserver/mods:universal-package-install - INSTALL_PACKAGES=ffmpeg volumes: - /docker/sabnzbd:/config - /downloads:/downloads ports: - 8080:8080 restart: unless-stopped ```
Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions