How to create a Docker container from an existing image
To create a Docker container from an existing image, you can use the docker run
command. Here are the steps:
- Pull or Build the Image: First, ensure you have the Docker image available locally. You can either pull an existing image from a registry like Docker Hub using
docker pull <image_name>
, or build an image from a Dockerfile usingdocker build -t <image_name> .
- Create and Start the Container: Once you have the image, run the following command to create and start a new container from that image:
docker run [OPTIONS] <image_name> [COMMAND] [ARG...]
Replace <image_name>
with the name of the image you want to use. You can also pass additional options and commands:
-d
or--detach
: Run the container in detached mode (in the background)-p
or--publish
: Publish a container’s port to the host (e.g.,-p 8080:80
to map host’s 8080 to container’s 80)-v
or--volume
: Bind mount a volume (e.g.,-v /host/path:/container/path
)-e
or--env
: Set environment variables--name
: Assign a name to the container[COMMAND]
: The command to run in the container (if different from the image’s default)
For example, to create and start a new container from the nginx
image in detached mode and map port 8080 on the host to 80 in the container, you would run:
docker run -d -p 8080:80 nginx
This will pull the nginx
image (if not available locally), create a new container instance from it, and start the container in the background while mapping port 8080 to 80.[1][5]
- Verify the Container: After running the
docker run
command, it will output the container ID. You can verify that the container is running usingdocker ps
to list all running containers.[1][4]
You can also create a container without starting it by using docker create
instead of docker run
. This is useful when you want to create and configure the container before running it later with docker start <container_id>
.[2]
Citations:
[1] https://blog.iron.io/how-to-create-a-docker-container/
[2] https://docs.docker.com/reference/cli/docker/container/create/
[3] https://datascientest.com/en/docker-tutorial-how-to-create-your-first-container
[4] https://docs.docker.com/get-started/02_our_app/
[5] https://stackoverflow.com/questions/39076153/how-to-create-container-in-docker