Using Docker involves several key concepts and commands to manage containers effectively. Here’s a concise guide to get you started:
1. Basic Concepts
- Images: Read-only templates used to create containers. You can think of an image as a snapshot of an application and its dependencies.
- Containers: Running instances of images. Containers are isolated environments where your applications run.
- Dockerfile: A script containing instructions to build a Docker image.
2. Common Docker Commands
Pulling an Image
To download an image from Docker Hub, use the docker pull command. For example, to pull the latest Nginx image:
docker pull nginx
Running a Container
To create and start a container from an image, use the docker run command. For example, to run an Nginx container:
docker run --name my-nginx -d -p 8080:80 nginx
--name my-nginx: Assigns a name to the container.-d: Runs the container in detached mode (in the background).-p 8080:80: Maps port 80 of the container to port 8080 on your host.
Listing Containers
To see all running containers, use:
docker ps
To see all containers (including stopped ones), use:
docker ps -a
Stopping a Container
To stop a running container, use:
docker stop my-nginx
Removing a Container
To remove a stopped container, use:
docker rm my-nginx
Building an Image from a Dockerfile
Create a Dockerfile with your application setup. For example:
# Use an official Python runtime as a parent image
FROM python:3.8-slim
# Set the working directory
WORKDIR /app
# Copy the current directory contents into the container at /app
COPY . /app
# Install any needed packages specified in requirements.txt
RUN pip install --no-cache-dir -r requirements.txt
# Make port 80 available to the world outside this container
EXPOSE 80
# Define environment variable
ENV NAME World
# Run app.py when the container launches
CMD ["python", "app.py"]
Build the image with:
docker build -t my-python-app .
3. Next Steps
- Explore Docker Compose: For managing multi-container applications.
- Check Docker Documentation: The official Docker documentation is a great resource for deeper learning.
Conclusion
Docker simplifies application deployment and management through containerization. By mastering these basic commands and concepts, you can effectively use Docker for your development and production needs.
If you have any questions or need further clarification, feel free to ask!
