Understanding Docker Containers and Images
Docker Containers
Docker containers are the runtime instances of Docker images. A container is a lightweight, standalone, and executable package that includes everything an application needs to run, such as the code, runtime, system tools, and libraries. Containers provide a consistent and predictable runtime environment, ensuring that applications run the same way regardless of the underlying infrastructure.
To create a new container, you can use the docker run
command:
docker run -it ubuntu:22.04 /bin/bash
This command will create a new container based on the ubuntu:22.04
image and start an interactive shell session within the container.
Docker Images
A Docker image is a read-only template that contains the application code, dependencies, and all the necessary components to run the application. Images are the building blocks of containers and are used to create and deploy Docker containers.
You can create your own Docker images or use pre-built images from public or private registries, such as Docker Hub. To build a custom Docker image, you can use a Dockerfile, which is a text file that contains instructions for building the image.
Here's an example Dockerfile that creates a simple "Hello, World!" application:
FROM ubuntu:22.04
RUN apt-get update && apt-get install -y nodejs
COPY app.js /app/
WORKDIR /app
CMD ["node", "app.js"]
This Dockerfile:
- Starts from the
ubuntu:22.04
base image
- Installs the Node.js runtime
- Copies the
app.js
file into the container
- Sets the working directory to
/app
- Specifies the command to run the application (
node app.js
)
To build the image, you can use the docker build
command:
docker build -t my-app .
This will create a new Docker image named my-app
based on the instructions in the Dockerfile.
Interacting with Docker Containers and Images
You can use various Docker commands to manage your containers and images, such as:
docker run
: Create and start a new container
docker ps
: List running containers
docker stop
: Stop a running container
docker rm
: Remove a container
docker build
: Build a new image from a Dockerfile
docker push
: Push an image to a registry
docker pull
: Pull an image from a registry
By understanding the concepts of Docker containers and images, you'll be able to leverage the power of containerization to streamline your application development and deployment processes.