🔧 Error Fixes
· 1 min read

Docker Container Exits Immediately — How to Fix It


$ docker ps -a
CONTAINER ID   STATUS                     NAMES
abc123         Exited (0) 2 seconds ago   my-app
def456         Exited (1) 1 second ago    my-api

Your container starts and immediately stops. Exit code 0 means it finished normally; exit code 1+ means it crashed.

Fix 1: No Long-Running Process

# ❌ Container has nothing to keep it running
FROM ubuntu
RUN apt-get update
# No CMD → exits immediately

# ✅ Add a foreground process
CMD ["node", "server.js"]
# Or for debugging:
CMD ["tail", "-f", "/dev/null"]

Fix 2: Check the Logs

# See why it exited
docker logs my-app

# Common: missing env vars, config errors, port conflicts

Fix 3: Process Running in Background

# ❌ Process daemonizes and container exits
CMD ["nginx"]  # Nginx daemonizes by default

# ✅ Run in foreground
CMD ["nginx", "-g", "daemon off;"]

Fix 4: Missing Environment Variables

# ❌ App crashes because DATABASE_URL isn't set
docker run my-app  # 💥

# ✅ Pass env vars
docker run -e DATABASE_URL=postgresql://... my-app
docker run --env-file .env my-app

Fix 5: Entrypoint Script Failing

# Check if entrypoint script has errors
docker run --entrypoint /bin/sh my-app -c "cat /entrypoint.sh"

# Common: Windows line endings (\r\n)
# Fix: convert to Unix line endings
sed -i 's/\r$//' entrypoint.sh

Fix 6: Debug Interactively

# Override the command and look around
docker run -it my-app /bin/sh

# Then manually run the start command to see errors
node server.js
📘