Docker 初学者指南 — 如何使用 docker-compose 创建客户端/服务器端

2025-06-07

Docker 初学者指南 — 如何使用 docker-compose 创建客户端/服务器端

如果你是一名开发者,想要了解 docker-compose 的使用方法?那么这篇文章就是为你量身定制的。

在对 Docker-Compose 进行简要介绍之后,您将能够使用 Docker 创建您的第一个客户端/服务器端应用程序。

本文假设您已经了解 Docker 的基础知识。如果没有,也不用担心!建议您阅读我的第一篇文章,了解 Docker 并学习如何创建您的第一个应用程序。

Docker 新手指南——如何创建你的第一个 Docker 应用程序
?你是一名开发者,想要开始使用 Docker?这篇文章就是为你量身定制的。

什么是 Docker-Compose?

Docker-Compose 是 Docker 提供的一个工具。简单来说,这个工具是为了解决项目中的架构问题而实现的。

正如您可能在我之前的文章中注意到的那样,我们创建了一个简单的程序,在启动时显示“Docker 很神奇!”。

不幸的是,当您是开发人员时,您很少会创建独立程序(不需要任何其他服务来运行的程序,例如数据库)。

但是,如何知道是否需要 Docker-Compose?很简单——如果您的应用程序需要运行多个服务,那么您就需要这个工具。例如,如果您创建了一个需要连接到数据库来验证用户身份的网站(这里有两个服务:网站和数据库)。

Docker-compose 为您提供了通过单个命令启动所有这些服务的可能性。

Docker和Docker-Compose之间的区别

Docker 用于管理您的应用程序的单个容器(服务)。

Docker-Compose 用于同时管理同一应用程序的多个容器。此工具提供与 Docker 相同的功能,但允许您构建更复杂的应用程序。Docker
Docker(单个容器) VS Docker-Compose(多个容器)(单个容器) vs Docker-Compose(多个容器)

典型用例

这个工具非常强大,可以让你快速部署架构复杂的应用程序。我会给你一个具体的案例研究,来证明你需要它。

想象一下,您是您的网络软件的骄傲创造者。

您的解决方案提供两个网站。第一个网站允许商店只需点击几下即可创建自己的在线商店。第二个网站专门用于客户支持。这两个网站与同一个数据库交互。

你开始取得成功,但你的服务器已无法满足需求。因此,你决定将整个软件迁移到另一台机器上。

很遗憾,你没有使用 docker-compose。所以你只能一个接一个地迁移并重新配置你的服务,希望没有遗漏任何内容。

如果您使用了 docker-compose,只需几条命令即可在新服务器上部署整个架构。现在您只需进行一些配置并加载数据库备份即可完成迁移。

现在让我们使用 Docker-Compose 创建您的第一个客户端/服务器端应用程序

现在您知道了 docker-compose 的用途,现在是时候创建您的第一个客户端/服务器端应用程序了!

本教程的目标是用 Python 创建一个小型网站(服务器),其中包含一个句子。该句子必须由一个 Python 程序(客户端)检索并显示。

注意:本教程假设您已在计算机上安装了 Docker,并且具备基础知识。如果不是这样,建议您参考我之前的文章

1. 创建你的项目

要创建您的第一个客户端/服务器应用程序,建议您在计算机上创建一个文件夹。该文件夹的根目录必须包含以下文件和文件夹:

  • docker-compose.yml ”文件(docker-compose 文件将包含创建不同服务所需的指令)。
  • 服务器”文件夹(此文件夹将包含设置服务器所需的文件)。
  • 客户端”文件夹(此文件夹将包含设置客户端所需的文件)。

通常你应该有这个文件夹架构:

    .
    ├── client/
    ├── docker-compose.yml
    └── server/
    2 directories, 1 file
Enter fullscreen mode Exit fullscreen mode

2.创建服务器

为了开始回忆 Docker 的基础知识,我们将从创建服务器开始。

2a. 创建文件

移至您的“服务器”文件夹并创建以下文件:

  • ' server.py ' 文件(包含服务器代码的 python 文件)。
  • ' index.html ' 文件(包含要显示的句子的 html 文件)。
  • Dockerfile ”文件(docker 文件将包含创建服务器环境所需的指令)。

通常您应该在以下路径“ server/ ”中拥有此文件夹架构:

    .
    ├── Dockerfile
    ├── index.html
    └── server.py
    0 directories, 3 files
Enter fullscreen mode Exit fullscreen mode

2b.编辑 Python 文件

您可以将以下代码添加到“ server.py ”文件中:

    #!/usr/bin/env python3

    # Import of python system libraries.
    # These libraries will be used to create the web server.
    # You don't have to install anything special, these libraries are installed with Python.
    import http.server
    import socketserver

    # This variable is going to handle the requests of our client on the server.
    handler = http.server.SimpleHTTPRequestHandler

    # Here we define that we want to start the server on port 1234. 
    # Try to remember this information it will be very useful to us later with docker-compose.
    with socketserver.TCPServer(("", 1234), handler) as httpd:
        # This instruction will keep the server running, waiting for requests from the client.
        httpd.serve_forever()
Enter fullscreen mode Exit fullscreen mode

这段代码将允许您在此文件夹中创建一个简单的 Web 服务器。它将检索 index.html 文件的内容并将其分享到网页上。

2c.编辑Html文件

您可以在' index.html '文件中添加以下句子

    Docker-Compose is magic!
Enter fullscreen mode Exit fullscreen mode

这个文件会在服务器启动的时候被共享,并显示这句话。

2d.编辑 Docker 文件

在这里,我们将创建一个基本的 Dockerfile,用于执行我们的 Python 文件。我们将使用官方创建的镜像来执行 Python。

    # Just a remember, dockerfile must always start by importing the base image.
    # We use the keyword 'FROM' to do that.
    # In our example, we want to import the python image (from DockerHub).
    # So, we write 'python' for the image name and 'latest' for the version.
    FROM python:latest

    # In order to launch our python code, we must import the 'server.py' and 'index.html' file.
    # We use the keyword 'ADD' to do that.
    # Just a remember, the first parameter 'server.py' is the name of the file on the host.
    # The second parameter '/server/' is the path where to put the file on the image.
    # Here we put files at the image '/server/' folder.
    ADD server.py /server/
    ADD index.html /server/

    # I would like to introduce something new, the 'WORKDIR' command.
    # This command changes the base directory of your image.
    # Here we define '/server/' as base directory (where all commands will be executed).
    WORKDIR /server/
Enter fullscreen mode Exit fullscreen mode

3. 创建您的客户端

为了继续提醒 Docker 的基础知识,我们将创建客户端。

3a. 创建文件

移至您的“客户端”文件夹并创建以下文件:

  • ' client.py ' 文件(包含客户端代码的 python 文件)。
  • 一个“ Dockerfile ”文件(docker 文件将包含创建客户端环境所需的指令)。

通常您应该在以下路径“ client/ ”中拥有此文件夹架构:

    .
    ├── client.py
    └── Dockerfile
    0 directories, 2 files
Enter fullscreen mode Exit fullscreen mode

3b.编辑 Python 文件

您可以将以下代码添加到“ client.py ”文件中:

    #!/usr/bin/env python3

    # Import of python system library.
    # This library is used to download the 'index.html' from server.
    # You don't have to install anything special, this library is installed with Python.
    import urllib.request

    # This variable contain the request on 'http://localhost:1234/'.
    # You must wondering what is 'http://localhost:1234'?
    # localhost: This means that the server is local.
    # 1234: Remember we define 1234 as the server port.
    fp = urllib.request.urlopen("http://localhost:1234/")

    # 'encodedContent' correspond to the server response encoded ('index.html').
    # 'decodedContent' correspond to the server response decoded (what we want to display).
    encodedContent = fp.read()
    decodedContent = encodedContent.decode("utf8")

    # Display the server file: 'index.html'.
    print(decodedContent)

    # Close the server connection.
    fp.close()
Enter fullscreen mode Exit fullscreen mode

此代码将允许您获取服务器网页的内容并显示它。

3c.编辑 Docker 文件

至于服务器,我们将创建一个基本的 Dockerfile,负责执行我们的 Python 文件。

    # Same thing than the 'server' Dockerfile.
    FROM python:latest

    # Same thing than the 'server' Dockerfile.
    # We import 'client.py' in '/client/' folder.
    ADD client.py /client/

    # I would like to introduce something new, the 'WORKDIR' command.
    # This command changes the base directory of your image.
    # Here we define '/client/' as base directory.
    WORKDIR /client/
Enter fullscreen mode Exit fullscreen mode

4. 回到 Docker-Compose

您可能已经注意到,我们创建了两个不同的项目,即服务器和客户端,两者都使用 Dockerfile。

到目前为止,您已经了解的基础知识没有任何改变。

现在我们将编辑存储库根目录中的“ docker-compose.yml ”。

注意:Docker-Compose 非常完善,本文旨在为您提供一个具体而典型的示例。因此,您不会看到所有关键字。

    # A docker-compose must always start by the version tag.
    # We use "3" because it's the last version at this time.
    version: "3"

    # You should know that docker-composes works with services.
    # 1 service = 1 container.
    # For example, a service maybe, a server, a client, a database...
    # We use the keyword 'services' to start to create services.
    services:
      # As we said at the beginning, we want to create: a server and a client.
      # That is two services.

      # First service (container): the server.
      # Here you are free to choose the keyword.
      # It will allow you to define what the service corresponds to.
      # We use the keyword 'server' for the server.
      server:
        # The keyword "build" will allow you to define
        # the path to the Dockerfile to use to create the image
        # that will allow you to execute the service.
        # Here 'server/' corresponds to the path to the server folder
        # that contains the Dockerfile to use.
        build: server/

        # The command to execute once the image is created.
        # The following command will execute "python ./server.py".
        command: python ./server.py

        # Remember that we defined in'server/server.py' 1234 as port.
        # If we want to access the server from our computer (outside the container),
        # we must share the content port with our computer's port.
        # To do this, the keyword 'ports' will help us.
        # Its syntax is as follows: [port we want on our machine]:[port we want to retrieve in the container]
        # In our case, we want to use port 1234 on our machine and
        # retrieve port 1234 from the container (because it is on this port that
        # we broadcast the server).
        ports:
          - 1234:1234

      # Second service (container): the client.
      # We use the keyword 'client' for the server.
      client:
        # Here 'client/ corresponds to the path to the client folder
        # that contains the Dockerfile to use.
        build: client/

        # The command to execute once the image is created.
        # The following command will execute "python ./client.py".
        command: python ./client.py

        # The keyword 'network_mode' is used to define the network type.
        # Here we define that the container can access to the 'localhost' of the computer.
        network_mode: host

        # The keyword'depends_on' allows you to define whether the service
        # should wait until other services are ready before launching.
        # Here, we want the 'client' service to wait until the 'server' service is ready.
        depends_on:
          - server
Enter fullscreen mode Exit fullscreen mode

5. 构建 Docker-Compose

设置好 docker-compose 后,需要构建客户端/服务器应用程序。此步骤与“docker build”命令相对应,但适用于不同的服务。

`$ docker-compose build`
Enter fullscreen mode Exit fullscreen mode

6. 运行 Docker-Compose

你的 docker-compose 已经搭建好了!现在就可以开始了!此步骤与“docker run”命令相对应,但应用于不同的服务。

`$ docker-compose up`
Enter fullscreen mode Exit fullscreen mode

好了,就是这样。你应该会在终端里看到“Doc​​ker-Compose is magic!”。

注意:如教程中所示,您的“服务器”服务使用计算机的 1234 端口来分发其内容。如果您在计算机上打开“ http://localhost:1234/ ”页面,您应该会看到“Doc​​ker-Compose is magic!”。

代码可用

如果您想检索完整的代码以便更简单地发现它或执行它,我已将其放在我的 Github 上供您使用。

-> GitHub:客户端服务器 Docker-Compose 示例

Docker 的有用命令

与往常一样,我准备了一份可能对您使用 docker-compose 有用的命令列表。

  • 停止容器并删除由“ docker-compose up ”创建的容器、图像...

    $ docker-compose down

  • 显示来自服务的日志输出(例如:' docker-compose logs -f client ')。

    $ docker-compose logs -f [service name]

  • 列出容器。

    $ docker-compose ps

  • 在正在运行的容器中执行命令(例如:“ docker-compose exec server ls ”)。

    $ docker-compose exec [service name] [command]

  • 列出图像。

    $ docker-compose images


如果您想要更多类似的内容,您可以在 Twitter 上关注我,我会在那里发布有关 Web 开发、自我提升以及我作为全栈开发人员的历程的推文!

文章来源:https://dev.to/herewecode/a-beginner-s-guide-to-docker-how-to-create-a-client-server-side-with-docker-compose-53p5
PREV
如何提高你的编程技能
NEXT
使用 NodeJS 拦截 HTTP 请求