Skip to main content

Start Docker Image

After building a Docker image, the next step is to start a container based on that image. Starting a Docker container allows you to run your application in an isolated and reproducible environment. Follow these steps to start a Docker image as a container:

Check Docker Images: Before starting a container, verify that the Docker image you want to run is available on your system. Open a terminal or command prompt and use the following command to list all the Docker images:

docker images

This command displays a list of Docker images, including the image you built or pulled from a registry.

Start a Container: To start a container, use the docker run command followed by the image name and any additional options you need. For example, to start a container based on the "myapp" image you built, use:

docker run myapp:latest

By default, this command starts the container in the foreground, attaching the container's standard input, output, and error streams to your terminal.

Detached Mode: If you want to start the container in the background (detached mode), use the -d option. For example:

docker run -d myapp:latest

This allows the container to run in the background without blocking your terminal.

Port Mapping: If your application listens on a specific port inside the container, and you want to access it from your host machine, you need to map the container port to a port on the host. Use the -p option to specify the port mapping. For example, to map container port 8080 to host port 5000, use:

docker run -p 5000:8080 myapp:latest

This enables you to access your application running inside the container using http://localhost:5000 on your host machine.

Name your Container: By default, Docker assigns a random name to the container when it starts. If you want to provide a specific name, use the --name option followed by the desired name. For example:

docker run --name my-container myapp:latest

This allows you to easily refer to the container using its assigned name.

Environment Variables: If your application requires environment variables, you can pass them to the container using the -e option. For example, to set the ENV_VARIABLE environment variable to "value", use:

docker run -e ENV_VARIABLE=value myapp:latest

This makes the specified environment variable available to your application inside the container.

Stop a Running Container: To stop a running container, use the docker stop command followed by the container ID or name. For example:

docker stop my-container

This gracefully stops the container, allowing it to perform any necessary cleanup before shutting down.

Starting a Docker image as a container allows your application to run in an isolated environment with its dependencies. You can start multiple containers based on the same image or different images, enabling easy scalability and application deployment.