One place for hosting & domains

      Containers

      How to Install Podman for Running Containers


      Podman is an open source containerization tool. Like Docker, Podman is a solution for creating, running, and managing containers. But Podman goes beyond Docker, using a secure daemonless process to run containers in rootless mode.

      For more on what Podman is and how it compares to Docker, you can refer to our guide
      Podman vs Docker. The guide familiarizes you with the basics of Podman and Docker and compares and contrast the two tools.

      In this tutorial, learn everything you need to install and start using Podman on your Linux system. By the end, you can run and manage containers using Podman.

      Before You Begin

      1. Familiarize yourself with our
        Getting Started with Linode guide, and complete the steps for setting your Linode’s hostname and timezone.

      2. This guide uses sudo wherever possible. Complete the sections of our
        How to Secure Your Server guide to create a standard user account, harden SSH access, and remove unnecessary network services.

      3. Update your system.

        • Debian or Ubuntu:

          sudo apt update && sudo apt upgrade
          
        • AlmaLinux, CentOS Stream, Fedora, or Rocky Linux:

          sudo dnf upgrade
          

      Note

      This guide is written for a non-root user. Commands that require elevated privileges are prefixed with sudo. If you’re not familiar with the sudo command, see the
      Users and Groups guide.

      How to Install Podman

      1. Podman is available through the default package managers on most Linux distributions.

        • AlmaLinux, CentOS Stream, Fedora, or Rocky Linux:

          sudo dnf install podman
          
        • Debian or Ubuntu:

          sudo apt install podman
          

          Note

          Podman is only available through the APT package manager for Debian 11 or Ubuntu 20.10 and later.

      2. Afterward, verify your installation by checking the installed Podman version:

        podman -v
        

        Your output may vary from what is shown here, but you are just looking to see that Podman installed successfully:

        podman version 4.1.1

      Configuring Podman for Rootless Usage

      Podman operates using root privileges by default – for instance, using the sudo preface for commands. However, Podman is also capable of running in rootless mode, an appealing feature when you want limited users to execute container actions securely.

      Docker can allow you to run commands as a limited user, but the Docker daemon still runs as root. This is a potential security issue with Docker, one that may allow limited users to execute privileged commands through the Docker daemon.

      Podman solves this with the option of a completely rootless setup, where containers operate in a non-root environment. Below you can find the steps to set up your Podman instance for rootless usage.

      1. Install the slirp4netns and fuse-overlayfs tools to support your rootless Podman operations.

        • AlmaLinux, CentOS Stream, Fedora, or Rocky Linux:

          sudo dnf install slirp4netns fuse-overlayfs
          
        • Debian or Ubuntu:

          sudo apt install slirp4netns fuse-overlayfs
          
      2. Add subuids and subgids ranges for your limited user. This example does so for the user example-user. It gives that user a sub-UID and sub-GID of 100000, each with a range of 65535 IDs:

        sudo usermod --add-subuids 100000-165535 --add-subgids 100000-165535 example-user
        

      With Podman installed, everything is ready for you to start running containers with it. These next sections walk you through the major features of Podman for finding container images and running and managing containers.

      Getting an Image

      Podman offers a few methods for procuring container images, which you can follow along with below. These section also give you a couple of images to start with, and which are used in later sections for further examples.

      Searching for Images

      Perhaps the most straightforward way to get started with a container is by finding an existing image in a registry. With Podman’s search command, you can find matching images in any container registries you have set up.

      Note

      Podman may come with some registries configured by default. However, on some systems, it may first be necessary to configure these registries manually. You can do this by opening the /etc/containers/registries.conf file with your preferred text editor and adding a line like the following to the end:

      unqualified-search-registries=['registry.access.redhat.com', 'registry.fedoraproject.org', 'docker.io', 'quay.io']
      

      You can replace the registries listed here with ones that you would like to look for container images on.

      Podman’s GitHub also has a registries.conf file
      here that you can use as an initial reference.

      This example searches for images matching the term buildah:

      podman search buildah
      

      Keep in mind that your matches may differ depending on the registries your Podman instance is configured with:

      NAME                                                            DESCRIPTION
      registry.access.redhat.com/ubi8/buildah                         Containerized version of Buildah
      registry.access.redhat.com/ubi9/buildah                         rhcc_registry.access.redhat.com_ubi9/buildah
      registry.redhat.io/rhel8/buildah                                Containerized version of Buildah
      registry.redhat.io/rhel9/buildah                                rhcc_registry.access.redhat.com_rhel9/builda...
      [...]

      Downloading an Image

      After searching the registries, you can use Podman to download, or pull, a particular image. This can be accomplished with Podman’s pull command followed by the name of the container image:

      podman pull buildah
      

      As the search output shows, there may be multiple registries matching a given container image:

      Resolved "buildah" as an alias (/etc/containers/registries.conf.d/shortnames.conf)
      Trying to pull quay.io/buildah/stable:latest...
      Getting image source signatures
      [...]

      But you can also be more specific. You can specify the entire image name, with the registry path, to pull from a specific location.

      For instance, this next example pulls the Buildah image from the docker.io registry:

      podman pull docker.io/buildah/buildah
      

      As you can see, it skipped the part where it resolves the shortname alias and pulls the Buildah image directly from the specified source:

      Trying to pull docker.io/buildah/buildah:latest...
      Getting image source signatures
      [...]

      Building an Image

      Like Docker, Podman also gives you the ability to create a container image from a file. Typically, this build process uses the Dockerfile format, though Podman supports the Containerfile format as well.

      You can learn more about crafting Dockerfiles in our guide
      How to Use a Dockerfile to Build a Docker Image. This guide also includes links to further tutorials with more in-depth coverage of Dockerfiles.

      But for now, as an example to see Podman’s build capabilities in action, you can use the following Dockerfile:

      File: Dockerfile
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      
      # Base on the most recently released Fedora
      FROM fedora:latest
      MAINTAINER ipbabble email [email protected] # not a real email
      
      # Install updates and httpd
      RUN echo "Updating all fedora packages"; dnf -y update; dnf -y clean all
      RUN echo "Installing httpd"; dnf -y install httpd && dnf -y clean all
      
      # Expose the default httpd port 80
      EXPOSE 80
      
      # Run the httpd
      CMD ["/usr/sbin/httpd", "-DFOREGROUND"]

      Place these contents in a file named Dockerfile. Then, working from the same directory the file is stored in, you can use the following Podman command to build an image from the file:

      podman build -t fedora-http-server .
      

      The -t option allows you to give the image a tag, or name – fedora-http-server in this case. The . at the end of the command specifies the directory in which the Dockerfile can be found, where a . represents the current directory.

      Keep reading onto the section below titled
      Running a Container Image to see how you can run a container from an image built as shown above.

      Podman’s build command works much like Docker’s, but is actually a subset of the build functionality within Buildah. In fact, Podman uses a portion of Buildah’s source code to implement its build function.

      Buildah offers more features and fine-grained control when it comes to building containers. For that reason, many see Podman and Buildah as complementary tools. Buildah provides a robust tool for crafting container images from both container files (e.g. Dockerfiles) and from scratch. Podman then excels at running and managing the resulting containers.

      You can learn more about Buildah, including steps for setup and usage, in our guide
      How to Use Buildah to Build OCI Container Images.

      Listing Local Images

      Once you have one or more images locally on your system, you can see them using Podman’s images command. This gives you a list of images that have been created or downloaded onto your system:

      podman images
      

      Following the two sections above — on downloading and then building container images — you could expect an output similar to:

      REPOSITORY                         TAG         IMAGE ID      CREATED       SIZE
      localhost/fedora-http-server       latest      f6f5a66c8a4d  2 hours ago   328 MB
      quay.io/buildah/stable             latest      eef9e8be5fea  2 hours ago  358 MB
      registry.fedoraproject.org/fedora  latest      3a66698e6040  2 hours ago  169 MB

      Running a Container Image

      With images either downloaded or created, you can begin using Podman to run containers.

      The process can be relatively straightforward with Podman’s run command, which just takes the name of the image to run a container from.

      Here is an example using the Buildah image downloaded above. This example runs the Buildah image, specifically executing the buildah command on the resulting container:

      podman run buildah buildah -v
      

      The -v option is included to output the version of the application:

      buildah version 1.26.2 (image-spec 1.0.2-dev, runtime-spec 1.0.2-dev)

      Containers’ operations can get more complicated from there, and Podman has plenty of features to support a wide range of needs when it comes to running containers.

      Take the fedora-http-server example created from a Dockerfile above. This example runs an HTTP server on the container’s port 80. The following command demonstrates how Podman lets you control how that container operates.

      The command runs the container, which automatically starts up an HTTP server. The -p option given here publishes the container’s port 80 to the local machine’s port 8080, while the --rm option automatically stops the container when it finishes running — a fitting solution for a quick test.

      podman run -p 8080:80 --rm fedora-http-server
      

      Now, on the machine where the image is running, use a cURL command to verify that the default web page is being served on port 8080:

      curl localhost:8080
      

      You should see the HTML of the Fedora HTTP Server Test Page:

      <!doctype html>
      <html>
        <head>
          <meta charset='utf-8'>
          <meta name='viewport' content='width=device-width, initial-scale=1'>
          <title>Test Page for the HTTP Server on Fedora</title>
          <style type="text/css">
            /*<![CDATA[*/
      
            html {
              height: 100%;
              width: 100%;
            }
              body {
      [...]

      Managing Containers and Images

      Podman prioritizes effectively running and managing containers. As such, it comes with plenty of commands for keeping track of and operating your containers.

      These next several sections walk through some of the most useful Podman operations, and can help you get the most out of your containers.

      Listing Containers

      Often those working with containers may keep a container or two, sometimes several containers, running in the background.

      To keep track of these containers, you can use Podman’s ps command. This lists the currently running containers on your system.

      For instance, if you are in the process of running the fedora-http-server container shown above, you can expect something like:

      podman ps
      
      CONTAINER ID  IMAGE                                COMMAND               CREATED        STATUS            PORTS                 NAMES
      daadb647b880  localhost/fedora-http-server:latest  /usr/sbin/httpd -...  8 seconds ago  Up 8 seconds ago  0.0.0.0:8080->80/tcp  suspicious_goodall

      And if you want to list all containers, not just the ones that are currently running, you can add the -a option to the command:

      podman ps -a
      

      The output of this command also includes the buildah command executed using podman run further above:

      CONTAINER ID  IMAGE                                COMMAND               CREATED             STATUS                     PORTS                 NAMES
      db71818eda38  quay.io/buildah/stable:latest        buildah -v            12 minutes ago      Exited (0) 12 minutes ago                        exciting_kowalevski
      daadb647b880  localhost/fedora-http-server:latest  /usr/sbin/httpd -...  About a minute ago  Up About a minute ago      0.0.0.0:8080->80/tcp  suspicious_goodall

      Starting and Stopping Containers

      Podman can individually control when to stop and start containers, using the stop and start commands, respectively. Each of these commands takes either the container ID or container name as an argument, both of which you can find using the ps command, as shown above.

      For example, you can stop the fedora-http-server container above with:

      podman stop daadb647b880
      

      Had this container been run without the --rm option, which automatically removes the container when it has stopped running, you could start the container back up simply with:

      podman start daadb647b880
      

      For either command, you could substitute the container name for its ID, as so:

      podman stop suspicious_goodall
      

      Removing a Container

      You can manually remove a container using Podman’s rm command, which, like the stop and start commands, takes either a container ID or name as an argument.

      podman rm daadb647b880
      

      Creating an Image from a Container

      Podman can render a container into an image using the commit command. This can be used to manually create an updated container image after components have been added to, removed from, or modified on a container.

      Like other container-related commands, this command takes the container ID or name as an argument. It’s also good practice to include an author name along with the commit, via the --author option:

      podman commit --author "Example User" daadb647b880
      

      As noted in the section above on creating images with Podman, Buildah tends to offer more features and control when it comes to creating container images. But Podman is certainly capable in many cases and may be enough to fit your given needs.

      Conclusion

      Podman offers not just a simple alternative to Docker, but a powerful containerization tool with the weight of secure, rootless operations. And, with this tutorial, you have what you need to start using Podman for running and managing your containers.

      Keep learning about effective tools for working with containers through the links on Podman, Buildah, and Dockerfiles provided in the course of this tutorial. Continue sharpening your Podman knowledge through the links provided at the end of this tutorial.

      More Information

      You may wish to consult the following resources for additional information
      on this topic. While these are provided in the hope that they will be
      useful, please note that we cannot vouch for the accuracy or timeliness of
      externally hosted materials.



      Source link

      Rails on Containers eBook


      Download the Complete eBook!

      Rails on Containers eBook in EPUB format

      Rails on Containers eBook in PDF format

      Introduction to the eBook

      This book is designed to introduce you to using containers and Kubernetes for full-stack development. You’ll learn how to develop a full-stack application using Ruby on Rails and PostgreSQL with Sidekiq, and how to manage them all — first with Docker, then with Docker Compose, and finally with Kubernetes.

      This book is based on the Rails on Containers tutorial series found on DigitalOcean Community. The topics that it covers include how to:

      1. Get started developing an application about sharks using the Ruby on Rails framework

      2. Extend the application’s data model to incorporate user submitted information about sharks

      3. Add the Stimulus JavaScript and Bootstrap CSS frameworks to your application to create visually appealing, interactive pages

      4. Integrate Sidekiq into your application to handle asynchronous data processing

      5. Containerize your application and streamline your development workflow using Docker Compose

      6. Migrate your Docker Compose development workflow to Kubernetes, finishing with a completely cloud-native application

      Each chapter is is designed to build progressively from the first. However, if you’re familiar with a topic, or are more interested in a particular section, feel free to jump to the chapter that best suits your purpose.

      Download the eBook

      You can download the eBook in either the EPUB or PDF format by following the links below.

      Download the Complete eBook!

      Rails on Containers eBook in EPUB format

      Rails on Containers eBook in PDF format

      If you’d like to learn more about app development using Rails visit the DigitalOcean Community’s Ruby on Rails section. Or if you want to continue learning about containers, Docker, and Kubernetes, you might be interested in the Kubernetes for Full-Stack Developers self-guided course.



      Source link

      How To Use Traefik v2 as a Reverse Proxy for Docker Containers on Ubuntu 20.04


      The author selected Girls Who Code to receive a donation as part of the Write for DOnations program.

      Introduction

      Docker can be an efficient way to run web applications in production, but you may want to run multiple applications on the same Docker host. In this situation, you’ll need to set up a reverse proxy. This is because you only want to expose ports 80 and 443 to the rest of the world.

      Traefik is a Docker-aware reverse proxy that includes a monitoring dashboard. Traefik v1 has been widely used for a while, and you can follow this earlier tutorial to install Traefik v1). But in this tutorial, you’ll install and configure Traefik v2, which includes quite a few differences.

      The biggest difference between Traefik v1 and v2 is that frontends and backends were removed and their combined functionality spread out across routers, middlewares, and services. Previously a backend did the job of making modifications to requests and getting that request to whatever was supposed to handle it. Traefik v2 provides more separation of concerns by introducing middlewares that can modify requests before sending them to a service. Middlewares make it easier to specify a single modification step that might be used by a lot of different routes so that they can be reused (such as HTTP Basic Auth, which you’ll see later). A router can also use many different middlewares.

      In this tutorial you’ll configure Traefik v2 to route requests to two different web application containers: a WordPress container and an Adminer container, each talking to a MySQL database. You’ll configure Traefik to serve everything over HTTPS using Let’s Encrypt.

      Prerequisites

      To complete this tutorial, you will need the following:

      Step 1 — Configuring and Running Traefik

      The Traefik project has an official Docker image, so you will use that to run Traefik in a Docker container.

      But before you get your Traefik container up and running, you need to create a configuration file and set up an encrypted password so you can access the monitoring dashboard.

      You’ll use the htpasswd utility to create this encrypted password. First, install the utility, which is included in the apache2-utils package:

      • sudo apt-get install apache2-utils

      Then generate the password with htpasswd. Substitute secure_password with the password you’d like to use for the Traefik admin user:

      • htpasswd -nb admin secure_password

      The output from the program will look like this:

      Output

      admin:$apr1$ruca84Hq$mbjdMZBAG.KWn7vfN/SNK/

      You’ll use this output in the Traefik configuration file to set up HTTP Basic Authentication for the Traefik health check and monitoring dashboard. Copy the entire output line so you can paste it later.

      To configure the Traefik server, you’ll create two new configuration files called traefik.toml and traefik_dynamic.toml using the TOML format. TOML is a configuration language similar to INI files, but standardized. These files let us configure the Traefik server and various integrations, or providers, that you want to use. In this tutorial, you will use three of Traefik’s available providers: api, docker, and acme. The last of these, acme, supports TLS certificates using Let’s Encrypt.

      Create and open traefik.toml using nano or your preferred text editor:

      First, you want to specify the ports that Traefik should listen on using the entryPoints section of your config file. You want two because you want to listen on port 80 and 443. Let’s call these web (port 80) and websecure (port 443).

      Add the following configurations:

      traefik.toml

      [entryPoints]
        [entryPoints.web]
          address = ":80"
          [entryPoints.web.http.redirections.entryPoint]
            to = "websecure"
            scheme = "https"
      
        [entryPoints.websecure]
          address = ":443"
      

      Note that you are also automatically redirecting traffic to be handled over TLS.

      Next, configure the Traefik api, which gives you access to both the API and your dashboard interface. The heading of [api] is all that you need because the dashboard is then enabled by default, but you’ll be explicit for the time being.

      Add the following code:

      traefik.toml

      ...
      [api]
        dashboard = true
      

      To finish securing your web requests you want to use Let’s Encrypt to generate valid TLS certificates. Traefik v2 supports Let’s Encrypt out of the box and you can configure it by creating a certificates resolver of the type acme.

      Let’s configure your certificates resolver now using the name lets-encrypt:

      traefik.toml

      ...
      [certificatesResolvers.lets-encrypt.acme]
        email = "your_email@your_domain"
        storage = "acme.json"
        [certificatesResolvers.lets-encrypt.acme.tlsChallenge]
      

      This section is called acme because ACME is the name of the protocol used to communicate with Let’s Encrypt to manage certificates. The Let’s Encrypt service requires registration with a valid email address, so to have Traefik generate certificates for your hosts, set the email key to your email address. You then specify that you will store the information that you will receive from Let’s Encrypt in a JSON file called acme.json.

      The acme.tlsChallenge section allows us to specify how Let’s Encrypt can verify that the certificate. You’re configuring it to serve a file as part of the challenge over port 443.

      Finally, you need to configure Traefik to work with Docker.

      Add the following configurations:

      traefik.toml

      ...
      [providers.docker]
        watch = true
        network = "web"
      

      The docker provider enables Traefik to act as a proxy in front of Docker containers. You’ve configured the provider to watch for new containers on the web network, which you’ll create soon.

      Our final configuration uses the file provider. With Traefik v2, static and dynamic configurations can’t be mixed and matched. To get around this, you will use traefik.toml to define your static configurations and then keep your dynamic configurations in another file, which you will call traefik_dynamic.toml. Here you are using the file provider to tell Traefik that it should read in dynamic configurations from a different file.

      Add the following file provider:

      traefik.toml

      • [providers.file]
      • filename = "traefik_dynamic.toml"

      Your completed traefik.toml will look like this:

      traefik.toml

      [entryPoints]
        [entryPoints.web]
          address = ":80"
          [entryPoints.web.http.redirections.entryPoint]
            to = "websecure"
            scheme = "https"
      
        [entryPoints.websecure]
          address = ":443"
      
      [api]
        dashboard = true
      
      [certificatesResolvers.lets-encrypt.acme]
        email = "your_email@your_domain"
        storage = "acme.json"
        [certificatesResolvers.lets-encrypt.acme.tlsChallenge]
      
      [providers.docker]
        watch = true
        network = "web"
      
      [providers.file]
        filename = "traefik_dynamic.toml"
      

      Save and close the file.

      Now let’s create traefik_dynamic.toml.

      The dynamic configuration values that you need to keep in their own file are the middlewares and the routers. To put your dashboard behind a password you need to customize the API’s router and configure a middleware to handle HTTP basic authentication. Let’s start by setting up the middleware.

      The middleware is configured on a per-protocol basis and since you’re working with HTTP you’ll specify it as a section chained off of http.middlewares. Next comes the name of your middleware so that you can reference it later, followed by the type of middleware that it is, which will be basicAuth in this case. Let’s call your middleware simpleAuth.

      Create and open a new file called traefik_dynamic.toml:

      • nano traefik_dynamic.toml

      Add the following code. This is where you’ll paste the output from the htpasswd command:

      traefik_dynamic.toml

      [http.middlewares.simpleAuth.basicAuth]
        users = [
          "admin:$apr1$ruca84Hq$mbjdMZBAG.KWn7vfN/SNK/"
        ]
      

      To configure the router for the api you’ll once again be chaining off of the protocol name, but instead of using http.middlewares, you’ll use http.routers followed by the name of the router. In this case, the api provides its own named router that you can configure by using the [http.routers.api] section. You’ll configure the domain that you plan on using with your dashboard also by setting the rule key using a host match, the entrypoint to use websecure, and the middlewares to include simpleAuth.

      Add the following configurations:

      traefik_dynamic.toml

      ...
      [http.routers.api]
        rule = "Host(`your_domain`)"
        entrypoints = ["websecure"]
        middlewares = ["simpleAuth"]
        service = "api@internal"
        [http.routers.api.tls]
          certResolver = "lets-encrypt"
      

      The web entry point handles port 80, while the websecure entry point uses port 443 for TLS/SSL. You automatically redirect all of the traffic on port 80 to the websecure entry point to force secure connections for all requests.

      Notice the last three lines here configure a service, enable tls, and configure certResolver to "lets-encrypt". Services are the final step to determining where a request is finally handled. The api@internal service is a built-in service that sits behind the API that you expose. Just like routers and middlewares, services can be configured in this file, but you won’t need to do that to achieve your desired result.

      Your completed traefik_dynamic.toml file will look like this:

      traefik_dynamic.toml

      [http.middlewares.simpleAuth.basicAuth]
        users = [
          "admin:$apr1$ruca84Hq$mbjdMZBAG.KWn7vfN/SNK/"
        ]
      
      [http.routers.api]
        rule = "Host(`your_domain`)"
        entrypoints = ["websecure"]
        middlewares = ["simpleAuth"]
        service = "api@internal"
        [http.routers.api.tls]
          certResolver = "lets-encrypt"
      

      Save the file and exit the editor.

      With these configurations in place, you will now start Traefik.

      Step 2 – Running the Traefik Container

      In this step you will create a Docker network for the proxy to share with containers. You will then access the Traefik dashboard. The Docker network is necessary so that you can use it with applications that are run using Docker Compose.

      Create a new Docker network called web:

      • docker network create web

      When the Traefik container starts, you will add it to this network. Then you can add additional containers to this network later for Traefik to proxy to.

      Next, create an empty file that will hold your Let’s Encrypt information. You’ll share this into the container so Traefik can use it:

      Traefik will only be able to use this file if the root user inside of the container has unique read and write access to it. To do this, lock down the permissions on acme.json so that only the owner of the file has read and write permission.

      Once the file gets passed to Docker, the owner will automatically change to the root user inside the container.

      Finally, create the Traefik container with this command:

      • docker run -d
      • -v /var/run/docker.sock:/var/run/docker.sock
      • -v $PWD/traefik.toml:/traefik.toml
      • -v $PWD/traefik_dynamic.toml:/traefik_dynamic.toml
      • -v $PWD/acme.json:/acme.json
      • -p 80:80
      • -p 443:443
      • --network web
      • --name traefik
      • traefik:v2.2

      This command is a little long. Let’s break it down.

      You use the -d flag to run the container in the background as a daemon. You then share your docker.sock file into the container so that the Traefik process can listen for changes to containers. You also share the traefik.toml and traefik_dynamic.toml configuration files into the container, as well as acme.json.

      Next, you map ports :80 and :443 of your Docker host to the same ports in the Traefik container so Traefik receives all HTTP and HTTPS traffic to the server.

      You set the network of the container to web, and you name the container traefik.

      Finally, you use the traefik:v2.2 image for this container so that you can guarantee that you’re not running a completely different version than this tutorial is written for.

      A Docker image’s ENTRYPOINT is a command that always runs when a container is created from the image. In this case, the command is the traefik binary within the container. You can pass additional arguments to that command when you launch the container, but you’ve configured all of your settings in the traefik.toml file.

      With the container started, you now have a dashboard you can access to see the health of your containers. You can also use this dashboard to visualize the routers, services, and middlewares that Traefik has registered. You can try to access the monitoring dashboard by pointing your browser to https://monitor.your_domain/dashboard/ (the trailing / is required).

      You will be prompted for your username and password, which are admin and the password you configured in Step 1.

      Once logged in, you’ll see the Traefik interface:

      Empty Traefik dashboard

      You will notice that there are already some routers and services registered, but those are the ones that come with Traefik and the router configuration that you wrote for the API.

      You now have your Traefik proxy running, and you’ve configured it to work with Docker and monitor other containers. In the next step you will start some containers for Traefik to proxy.

      Step 3 — Registering Containers with Traefik

      With the Traefik container running, you’re ready to run applications behind it. Let’s launch the following containers behind Traefik:

      1. A blog using the official WordPress image.
      2. A database management server using the official Adminer image.

      You’ll manage both of these applications with Docker Compose using a docker-compose.yml file.

      Create and open the docker-compose.yml file in your editor:

      Add the following lines to the file to specify the version and the networks you’ll use:

      docker-compose.yml

      version: "3"
      
      networks:
        web:
          external: true
        internal:
          external: false
      

      You use Docker Compose version 3 because it’s the newest major version of the Compose file format.

      For Traefik to recognize your applications, they must be part of the same network, and since you created the network manually, you pull it in by specifying the network name of web and setting external to true. Then you define another network so that you can connect your exposed containers to a database container that you won’t expose through Traefik. You’ll call this network internal.

      Next, you’ll define each of your services, one at a time. Let’s start with the blog container, which you’ll base on the official WordPress image. Add this configuration to the bottom of the file:

      docker-compose.yml

      ...
      
      services:
        blog:
          image: wordpress:4.9.8-apache
          environment:
            WORDPRESS_DB_PASSWORD:
          labels:
            - traefik.http.routers.blog.rule=Host(`blog.your_domain`)
            - traefik.http.routers.blog.tls.enabled=true
            - traefik.http.routers.blog.tls.cert-provider=lets-encrypt
            - traefik.port=80
          networks:
            - internal
            - web
          depends_on:
            - mysql
      

      The environment key lets you specify environment variables that will be set inside of the container. By not setting a value for WORDPRESS_DB_PASSWORD, you’re telling Docker Compose to get the value from your shell and pass it through when you create the container. You will define this environment variable in your shell before starting the containers. This way you don’t hard-code passwords into the configuration file.

      The labels section is where you specify configuration values for Traefik. Docker labels don’t do anything by themselves, but Traefik reads these so it knows how to treat containers. Here’s what each of these labels does:

      • traefik.http.routers.adminer.rule=Host(`blog.your_domain`) creates a new router for your container and then specifies the routing rule used to determine if a request matches this container.
      • traefik.routers.custom_name.tls=true specifies that this router should use TLS.
      • traefik.routers.custom_name.tls.certResolver=lets-encrypt specifies that the certificates resolver that you created earlier called lets-encrypt should be used to get a certificate for this route.
      • traefik.port specifies the exposed port that Traefik should use to route traffic to this container.

      With this configuration, all traffic sent to your Docker host on port 80 or 443 with the domain of blog.your_domain will be routed to the blog container.

      You assign this container to two different networks so that Traefik can find it via the web network and it can communicate with the database container through the internal network.

      Lastly, the depends_on key tells Docker Compose that this container needs to start after its dependencies are running. Since WordPress needs a database to run, you must run your mysql container before starting your blog container.

      Next, configure the MySQL service:

      docker-compose.yml

      services:
      ...
        mysql:
          image: mysql:5.7
          environment:
            MYSQL_ROOT_PASSWORD:
          networks:
            - internal
          labels:
            - traefik.enable=false
      

      You’re using the official MySQL 5.7 image for this container. You’ll notice that you’re once again using an environment item without a value. The MYSQL_ROOT_PASSWORD and WORDPRESS_DB_PASSWORD variables will need to be set to the same value to make sure that your WordPress container can communicate with the MySQL. You don’t want to expose the mysql container to Traefik or the outside world, so you’re only assigning this container to the internal network. Since Traefik has access to the Docker socket, the process will still expose a router for the mysql container by default, so you’ll add the label traefik.enable=false to specify that Traefik should not expose this container.

      Finally, define the Adminer container:

      docker-compose.yml

      services:
      ...
        adminer:
          image: adminer:4.6.3-standalone
          labels:
            - traefik.http.routers.adminer.rule=Host(`db-admin.your_domain`)
            - traefik.http.routers.adminer.tls=true
            - traefik.http.routers.adminer.tls.certresolver=lets-encrypt
            - traefik.port=8080
          networks:
            - internal
            - web
          depends_on:
            - mysql
      

      This container is based on the official Adminer image. The network and depends_on configuration for this container exactly match what you’re using for the blog container.

      The line traefik.http.routers.adminer.rule=Host(`db-admin.your_domain`) tells Traefik to examine the host requested. If it matches the pattern of db-admin.your_domain, Traefik will route the traffic to the adminer container over port 8080.

      Your completed docker-compose.yml file will look like this:

      docker-compose.yml

      version: "3"
      
      networks:
        web:
          external: true
        internal:
          external: false
      
      services:
        blog:
          image: wordpress:4.9.8-apache
          environment:
            WORDPRESS_DB_PASSWORD:
          labels:
            - traefik.http.routers.blog.rule=Host(`blog.your_domain`)
            - traefik.http.routers.blog.tls=true
            - traefik.http.routers.blog.tls.certresolver=lets-encrypt
            - traefik.port=80
          networks:
            - internal
            - web
          depends_on:
            - mysql
      
        mysql:
          image: mysql:5.7
          environment:
            MYSQL_ROOT_PASSWORD:
          networks:
            - internal
          labels:
            - traefik.enable=false
      
        adminer:
          image: adminer:4.6.3-standalone
          labels:
          labels:
            - traefik.http.routers.adminer.rule=Host(`db-admin.your_domain`)
            - traefik.http.routers.adminer.tls=true
            - traefik.http.routers.adminer.tls.certresolver=lets-encrypt
            - traefik.port=8080
          networks:
            - internal
            - web
          depends_on:
            - mysql
      

      Save the file and exit the text editor.

      Next, set values in your shell for the WORDPRESS_DB_PASSWORD and MYSQL_ROOT_PASSWORD variables:

      • export WORDPRESS_DB_PASSWORD=secure_database_password
      • export MYSQL_ROOT_PASSWORD=secure_database_password

      Substitute secure_database_password with your desired database password. Remember to use the same password for both WORDPRESS_DB_PASSWORD and MYSQL_ROOT_PASSWORD.

      With these variables set, run the containers using docker-compose:

      Now watch the Traefik admin dashboard while it populates.

      Populated Traefik dashboard

      If you explore the Routers section you will find routers for adminer and blog configured with TLS:

      HTTP Routers w/ TLS

      Navigate to blog.your_domain, substituting your_domain with your domain. You’ll be redirected to a TLS connection and you can now complete the WordPress setup:

      WordPress setup screen

      Now access Adminer by visiting db-admin.your_domain in your browser, again substituting your_domain with your domain. The mysql container isn’t exposed to the outside world, but the adminer container has access to it through the internal Docker network that they share using the mysql container name as a hostname.

      On the Adminer login screen, enter root for Username, enter mysql for Server, and enter the value you set for MYSQL_ROOT_PASSWORD for the Password. Leave Database empty. Now press Login.

      Once logged in, you’ll see the Adminer user interface.

      Adminer connected to the MySQL database

      Both sites are now working, and you can use the dashboard at monitor.your_domain to keep an eye on your applications.

      Conclusion

      In this tutorial, you configured Traefik v2 to proxy requests to other applications in Docker containers.

      Traefik’s declarative configuration at the application container level makes it easy to configure more services, and there’s no need to restart the traefik container when you add new applications to proxy traffic to since Traefik notices the changes immediately through the Docker socket file it’s monitoring.

      To learn more about what you can do with Traefik v2, head over to the official Traefik documentation.



      Source link