Guide Docker Beginner

4. Container Lifecycle

Create, start, inspect, stop, and remove a container.

1 min read

Run a Web Server

docker run -d --name docker-course-web -p 127.0.0.1:8080:80 nginx:alpine
docker ps
docker logs docker-course-web

Open http://localhost:8080. The -d option starts the container in the background; it does not keep an application alive after its main process exits.

Lifecycle Commands

docker stop docker-course-web
docker ps -a
docker start docker-course-web
docker exec docker-course-web nginx -t
docker inspect docker-course-web

Stopping a container preserves its writable layer. Starting it again reuses that same container. Creating another container from the image produces a separate writable layer.

Cleanup

docker stop docker-course-web
docker rm docker-course-web

These commands remove only the named practice container.

Common Mistakes

  • Treating an exited container as a deleted container.
  • Running a short-lived command and expecting the container to stay running.
  • Using exec on a stopped container.

Practice

Compare the container ID before and after stop and start. It should remain the same.

Quick Interview Answer

A container lives as long as its main process. Stop and start reuse an existing container; run creates a new one.


Previous: 3. Docker Architecture | Next: 5. Images and Registries

Add More Questions to This Guide

Know a question that should be here? Share it and help the community!

Open Google Form