Как получить доступ к веб-приложению, работающему в контейнере Docker

DockerDockerBeginner
Практиковаться сейчас

💡 Этот учебник переведен с английского с помощью ИИ. Чтобы просмотреть оригинал, вы можете перейти на английский оригинал

Introduction

This tutorial will guide you through the process of accessing a web application running in a Docker container. You will learn the fundamentals of Docker containers, deploy a simple web application, and discover how to access it from your host machine. This knowledge is essential for developing and testing web applications using Docker.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL docker(("Docker")) -.-> docker/ContainerOperationsGroup(["Container Operations"]) docker(("Docker")) -.-> docker/ImageOperationsGroup(["Image Operations"]) docker(("Docker")) -.-> docker/DockerfileGroup(["Dockerfile"]) docker/ContainerOperationsGroup -.-> docker/run("Run a Container") docker/ContainerOperationsGroup -.-> docker/ps("List Running Containers") docker/ContainerOperationsGroup -.-> docker/stop("Stop Container") docker/ContainerOperationsGroup -.-> docker/rm("Remove Container") docker/ContainerOperationsGroup -.-> docker/logs("View Container Logs") docker/ImageOperationsGroup -.-> docker/images("List Images") docker/DockerfileGroup -.-> docker/build("Build Image from Dockerfile") subgraph Lab Skills docker/run -.-> lab-415069{{"Как получить доступ к веб-приложению, работающему в контейнере Docker"}} docker/ps -.-> lab-415069{{"Как получить доступ к веб-приложению, работающему в контейнере Docker"}} docker/stop -.-> lab-415069{{"Как получить доступ к веб-приложению, работающему в контейнере Docker"}} docker/rm -.-> lab-415069{{"Как получить доступ к веб-приложению, работающему в контейнере Docker"}} docker/logs -.-> lab-415069{{"Как получить доступ к веб-приложению, работающему в контейнере Docker"}} docker/images -.-> lab-415069{{"Как получить доступ к веб-приложению, работающему в контейнере Docker"}} docker/build -.-> lab-415069{{"Как получить доступ к веб-приложению, работающему в контейнере Docker"}} end

Understanding Docker and Running a Test Container

Docker is a platform that uses containerization to package applications and their dependencies together. This allows applications to run consistently across different environments.

Verifying Docker Installation

First, let's check if Docker is properly installed on your system:

docker --version

You should see output similar to this, showing the Docker version:

Docker version 20.10.21, build baeda1f

Understanding Docker Images and Containers

In Docker terminology:

  • A Docker image is a template containing the application code, libraries, and dependencies
  • A Docker container is a running instance of an image

Think of a Docker image as a blueprint and a Docker container as a building created from that blueprint.

Running Your First Docker Container

Let's run a simple container to verify Docker is working correctly:

docker run hello-world

You should see output like this:

Hello from Docker!
This message shows that your installation appears to be working correctly.

To generate this message, Docker took the following steps:
 1. The Docker client contacted the Docker daemon.
 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
 3. The Docker daemon created a new container from that image which runs the
    executable that produces the output you are currently reading.
 4. The Docker daemon streamed that output to the Docker client, which sent it
    to your terminal.
...

This confirms that Docker is working correctly on your system.

Basic Docker Commands

Here are some essential Docker commands you should know:

  1. To list all running containers:
docker ps
  1. To list all containers (including stopped ones):
docker ps -a
  1. To list all Docker images on your system:
docker images

Try these commands and observe the outputs. After running the hello-world container, you should see it listed when you run docker ps -a (but not in docker ps since it exits immediately after displaying the message).

Creating a Simple Web Application

In this step, we'll create a simple web application using Python and Flask that we can deploy in a Docker container.

Setting Up the Application Files

First, let's create a new directory for our web application:

mkdir -p ~/project/my-web-app
cd ~/project/my-web-app

Now, let's create a simple Flask application. Create a file called app.py using the nano editor:

nano app.py

Add the following Python code to the file:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello():
    return "<h1>Hello from Docker!</h1><p>This is a simple web application running in a Docker container.</p>"

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

Press Ctrl+O followed by Enter to save the file, then Ctrl+X to exit nano.

Next, create a requirements.txt file to specify our application's dependencies:

nano requirements.txt

Add the following line to the file:

flask==2.0.1

Press Ctrl+O followed by Enter to save the file, then Ctrl+X to exit nano.

Creating a Dockerfile

Now, let's create a Dockerfile to define how our application should be containerized:

nano Dockerfile

Add the following content to the file:

FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app.py .
EXPOSE 5000
CMD ["python", "app.py"]

This Dockerfile does the following:

  1. Uses a lightweight Python 3.9 image as the base
  2. Sets the working directory to /app
  3. Copies the requirements file and installs dependencies
  4. Copies the application code
  5. Exposes port 5000 for incoming connections
  6. Specifies the command to run when the container starts

Press Ctrl+O followed by Enter to save the file, then Ctrl+X to exit nano.

Building the Docker Image

Now, let's build a Docker image from our Dockerfile:

docker build -t my-flask-app .

The -t flag tags our image with the name my-flask-app. The . at the end specifies that the Dockerfile is in the current directory.

You should see output similar to this:

Sending build context to Docker daemon  x.xxxkB
Step 1/6 : FROM python:3.9-slim
 ---> xxxxxxxxxx
Step 2/6 : WORKDIR /app
 ---> Using cache
 ---> xxxxxxxxxx
...
Successfully built xxxxxxxxxx
Successfully tagged my-flask-app:latest

Now, check that your image was created:

docker images | grep my-flask-app

You should see your newly created image in the list.

Running the Web Application in a Docker Container

Now that we have built our Docker image, let's run it as a container and access the web application.

Running the Container

To run the container and map the port so we can access the web application, use the following command:

docker run -d -p 5000:5000 --name my-web-container my-flask-app

This command does the following:

  • -d: Runs the container in detached mode (in the background)
  • -p 5000:5000: Maps port 5000 from the container to port 5000 on the host
  • --name my-web-container: Assigns a name to the container
  • my-flask-app: Specifies the image to use

Verifying the Container is Running

Let's check that our container is running:

docker ps

You should see output similar to this:

CONTAINER ID   IMAGE          COMMAND           CREATED          STATUS          PORTS                    NAMES
xxxxxxxxxxxx   my-flask-app   "python app.py"   xx seconds ago   Up xx seconds   0.0.0.0:5000->5000/tcp   my-web-container

Accessing the Web Application

Now, you can access the web application in two ways:

  1. Using curl from the command line:
curl http://localhost:5000

You should see the HTML response:

<h1>Hello from Docker!</h1><p>This is a simple web application running in a Docker container.</p>
  1. Using a web browser:
    • Click on the web browser icon in the desktop environment
    • Enter http://localhost:5000 in the address bar
    • You should see "Hello from Docker!" followed by the description text

Understanding Port Mapping

When we run a container with -p 5000:5000, we are creating a mapping between:

  • The host port (first number): 5000
  • The container port (second number): 5000

This means that any traffic sent to port 5000 on the host machine will be forwarded to port 5000 inside the container.

We could also use different port numbers. For example, -p 8080:5000 would map host port 8080 to container port 5000, allowing you to access the application at http://localhost:8080.

Inspecting Container Logs

If you need to see the logs from the container (which can be helpful for debugging), use:

docker logs my-web-container

You should see the Flask application startup messages.

Stopping and Removing the Container

To stop the container, use:

docker stop my-web-container

To remove the stopped container, use:

docker rm my-web-container

You can also stop and remove a container in a single command:

docker rm -f my-web-container

This is useful during development when you want to rebuild and rerun your container quickly.

Advanced Docker Container Management

Now that you have successfully run your web application in a Docker container, let's explore some additional features and techniques for managing Docker containers.

Running Multiple Instances

You can run multiple instances of your web application on different ports. This is useful for testing or running different versions of your app simultaneously.

First, let's stop and remove our previous container:

docker rm -f my-web-container

Now, let's run two instances of our web application on different ports:

docker run -d -p 5000:5000 --name web-app-1 my-flask-app
docker run -d -p 5001:5000 --name web-app-2 my-flask-app

Verify that both containers are running:

docker ps

You should see two containers running:

CONTAINER ID   IMAGE          COMMAND           CREATED          STATUS          PORTS                    NAMES
xxxxxxxxxxxx   my-flask-app   "python app.py"   xx seconds ago   Up xx seconds   0.0.0.0:5001->5000/tcp   web-app-2
xxxxxxxxxxxx   my-flask-app   "python app.py"   xx seconds ago   Up xx seconds   0.0.0.0:5000->5000/tcp   web-app-1

Now you can access the same application on two different ports:

  • http://localhost:5000
  • http://localhost:5001

Container Resource Limits

Docker allows you to set resource limits for your containers. This is useful for preventing a container from consuming too many system resources.

Let's stop and remove our previous containers:

docker rm -f web-app-1 web-app-2

Now, let's run a container with memory and CPU limits:

docker run -d -p 5000:5000 --name limited-container --memory=512m --cpus=0.5 my-flask-app

This command creates a container with:

  • A maximum of 512MB of memory
  • A maximum of 0.5 CPU cores

Verify that the container is running:

docker ps

Container Environment Variables

Environment variables are a common way to configure applications in Docker containers. Let's modify our Flask application to use an environment variable:

docker rm -f limited-container

Create a new version of the app.py file:

cd ~/project/my-web-app
nano app_env.py

Add the following code:

import os
from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello():
    app_name = os.environ.get('APP_NAME', 'Default App')
    return f"<h1>Hello from {app_name}!</h1><p>This is a simple web application running in a Docker container.</p>"

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

Press Ctrl+O followed by Enter to save the file, then Ctrl+X to exit nano.

Create a new Dockerfile:

nano Dockerfile-env

Add the following content:

FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app_env.py ./app.py
EXPOSE 5000
CMD ["python", "app.py"]

Press Ctrl+O followed by Enter to save the file, then Ctrl+X to exit nano.

Build a new image:

docker build -t my-flask-app-env -f Dockerfile-env .

Now, run the container with an environment variable:

docker run -d -p 5000:5000 --name env-container -e APP_NAME="Customized App" my-flask-app-env

Access the web application:

curl http://localhost:5000

You should see:

<h1>Hello from Customized App!</h1><p>This is a simple web application running in a Docker container.</p>

This demonstrates how to pass configuration to your containerized applications using environment variables.

Summary

In this lab, you learned how to access a web application running in a Docker container. You created a simple Flask web application, containerized it using Docker, and accessed it from your host machine using port mapping.

Key concepts covered:

  • Understanding Docker images and containers
  • Creating a simple web application with Flask
  • Building a Docker image with a Dockerfile
  • Running and accessing a containerized web application
  • Managing Docker containers with various commands
  • Running multiple container instances on different ports
  • Setting resource limits for containers
  • Using environment variables for container configuration

These skills provide a solid foundation for working with containerized applications and will help you deploy and test web applications efficiently using Docker.