信息技术

The IMAIOS infrastructure is now managed with Docker

  • Valentin Faïsse
  • 2022/8/11
  • 在2022/4/8更新

Valentin Faïsse, backend web developer, shares his feedback on Docker technology. He delivers tips that will save you time and also details the other tools used for this project (Fargate, Solr, Fastly...).

At IMAIOS we love anatomy and technology, and we have combined the two to develop a suite of tools for all medical professionals and students. Behind our website and our mobile applications, there is a vital element that is not often talked about: our infrastructure.

In 2020, we noticed that the website was aging, the original team was no longer there and that it was difficult to make it evolve. The decision was made to completely redo the site, and a few months later the infrastructure that goes with it.

State of the art

Several reasons pushed us, or even forced us, to start this major overhaul of our main site, but we didn’t need to change our infrastructure. 

We could have kept the same EC2, the same CI/CD or the same dashboard, but why not use new technologies when you have the opportunity to change everything.

The IMAIOS site was (and will be for a few more weeks) a traditional site like the majority of sites a few years ago.

We have started by creating our VPC, subnets, security groups, roles and AWS is providing EC2. We have installed all the services we need, uploaded our PHP files, our configurations, run 2 or 3 commands and the site is now up and running. Other than a few updates, security patches and other optimizations, this is what the site will run on for several years.

Over the next few years, we will improve the EC2 configuration steps and the CI/CD with in-house bash scripts. We will add some services like Fastly and Solr (on EC2). To develop with a working environment as close as possible to the production environment, each developer has an EC2 identical to the production one, but with a minimum of resources in order to reduce costs.

As time goes by, our traffic has increased and so have the attacks. To cope with this, we have added 2 EC2s, but as we haven’t configured auto scaling we have 3 large EC2s at rest most of the time.

Today we have EC2s that are difficult to update, a large AWS bill, code that has been developed for several years and for which most of the authors are no longer around, and an obsolete CMS (eZ Publish 5) that is constraining us more and more in our evolutions.

In 2020, the decision was made to stop developing the site and start a complete redesign. At the time there were no plans to change the infrastructure and the developers continued to work as usual on EC2.

I joined IMAIOS in 2020, in the middle of COVID, as backend developer. The first weeks and my first developments were going well, but a sense of nostalgia for my previous ways of working started to creep in. It's been a while since I had to upload my files on a remote server and patiently wait for each reload.

Happy with my previous experiences with Docker, I started to miss The Whale. Following discussions with the technical directors, the local Docker stack was born. Being very well equipped with hardware, it runs without any problems, and WSL lets us stay on Windows like all our developers. A few weeks later, the decision was made to redo the infrastructure on Docker for the new site.

New site same feature

The first commit of the Git repository used for the site currently in production dates back to 2011.

At that time, we were using version 4.5 of the eZ Publish CMS. Until last year, we followed the version upgrades of the CMS until the eZ Platform 2.5 version.

For the record, the eZ Publish CMS at the time was a tool entirely developed in-house by the company eZ System since 1999. From version 5 onwards it will start using Symfony 2 and then change its name to eZ Platform to be completely redone under Symfony 5. The eZ System company will also change its name to Ibexa.

Since 2021 our version of the CMS is no longer officially supported, part of our application source code is more than 10 years old, the original team has completely changed and any new functionalities are almost impossible to release.

So we have no choice but to completely redesign the site.

Happy with our experience with eZ Platform, we prefer to stick with this tool. We will start with the free version 2.5 under Symfony 5, and then move on to version 3. This will also allow us to use PHP 7 and then PHP 8.

In terms of software architecture, we have chosen to develop following the principles of hexagonal architecture and Domain Driven Design. We will have to do some training internally so that everyone understands and adopts the new developing methods.

New Docker infrastructure

The biggest change compared to the old architecture will be the use of Docker technology. This raises the question of which AWS service to use, between ECS, EKS or Fargate. Given my lack of experience in this area, we will choose the simplest.

Docker

Using Docker has completely changed our infrastructure, but also the way we work locally. No more remote development servers, no more ssh connections to send code to the server, no more latencies for synchronization and page loading. Today, each developer has a local development instance very close to the production instance.

Unlike our legacy infrastructure where most services are installed on a single server, the Docker philosophy is that each service has its own container.

Container source

Locally, each developer will make a volume of his working directory with the Front and Worker containers. For Fargate, a "source" container will be created and will serve as a volume for the other containers. This "source" container will not contain any service, only the source code of the application. It will be built each time the source code is updated on the Git repository and the Fargate tasks will be updated with this new version.

There are several advantages to doing this. It avoids embedding source code in other containers and having to rebuild them all at each update. It also makes the containers lighter. No need to set up a file system, EFS, EBS or others to give access to this code. Now each Fargate task embeds its own version of the code.

It also allows you to put all the source retrieval/compilation logic in a Dockerfile. And thanks to Docker's multi-stage build system, each stage can have dependencies to build tools that don't need to be embedded in the final container version. In our case, several stages will use official images of PHP, NodeJs and Yarn to retrieve/compile Symfony vendors and Javascript node modules without these tools being in the final container, which will just be an alpine image with the compiled sources. The other interest of multi-stage is to be able to build several stages in parallel and to be able to reuse stages from previous versions if the dependencies haven't changed. All this to be able to re-build the source container in a few minutes.

Frontal / Worker

The Fargate task in charge of processing incoming requests will be composed of 2 main containers (we will see the other containers later) which are, 1 for Nginx and 1 for PHP in FPM mode. For performance reasons, PHP will listen to a socket, rather than an IP, which will be mounted in volume in the Nginx container.

The Worker will be a PHP container in CLI mode whose Docker entrypoint will be a PHP command that will launch the Symfony Messenger service in continuous listening mode. This worker will allow us to process PHP tasks in asynchronous mode, by reading the messages sent by the Frontend server in SQS.

The same container Worker can be used to launch Fargate tasks programmed with custom commands.

Log

To facilitate log management, Fargate has implemented a log router. It allows you to listen to the standard output of the containers and transfer them to a container which will be able to decide how to treat them. In our case, each task contains a log container (with Fluent Bit) which will receive the logs of the other containers of this same task.

Monitoring

For monitoring, all our tasks will also have a NewRelic container that will transfer all the metrics from the containers to the NewRelic servers. We will also have a BlackFire container that will allow us to analyze any PHP trace on demand.

Load Balancer

Our application uses Solr, on our legacy infrastructure, this one is installed in standalone mode and thus becomes a SPOF. If Solr becomes unavailable, most of our pages will be inaccessible. To compensate for this, we have put Solr in Cloud mode with 2 nodes. Since the application cannot be configured with 2 Solr addresses, we need to use a Load Balancer. We chose to use a LoadBalancer in each task rather than a single Load Balancer managed by AWS, which would itself become an SPOF.

To do this, each Frontend or Worker task has its own container that serves as a Load Balancer. We used SideKick (from MinIO), which is very light and does only what we need. It will know the address of the 2 Solr nodes and will transfer (in round robin mode) the requests to the Solr node. It will also do a health check to determine the state of the servers.

Fargate

Fargate is relatively easy to use, you just have to define tasks to configure a set of containers and services in charge of launching the tasks, a bit like Auto Scaling Groups for EC2. You don't even need to worry about the EC2s on which your tasks will be launched, you just need to define the necessary resources in your tasks.

So we have 4 different types of tasks that will be used to run front-ends with Nginx and PHP in FPM mode, workers for asynchronous processing in PHP Cli, Solr in Cloud mode and Zookeeper needed for SolrCloud. The front-ends and workers will be in auto scaling, there will be 2 Solr for redundancy and 3 Zookeeper. And all this will be distributed over 3 availability zones.

Fargate also allows you to schedule when specific tasks should be executed. You can schedule them like a CRON or in response to an event. Once the execution is finished, they will be turned off.

Since Fargate doesn't allow tasks with more than 8GB of RAM and 4 vCPUs, we are forced to use ECS to run Solr. You just have to configure EC2 with the resources you need and a special ECS AMI, and Fargate will start your tasks on your EC2. Be careful to use an Auto Scaling Groups so that your EC2s restart automatically in case of a shutdown.

Fargate also simplifies SPOT management. You no longer need to define criteria (maximum price, type of instance, etc.) according to which you will save money. Fargate makes everything transparent, you just need to say which tasks can be launched in SPOT. It is also possible to mix SPOT and OnDemand launches of the same task simultaneously.
When Fargate wants to shut down a task, it will send a SIGTERM signal to each container before sending the SIGKILL signal 30 seconds later. This allows the process inside the containers to be informed of the container shutdown and to be able to shut down properly.

CloudFormation

Using the AWS console to experiment or discover a feature is the easiest and most intuitive. But when it comes to repeating one or more operations X times in a row, duplicating an existing configuration on another zone or another VPC can quickly become time consuming. Especially when an entire infrastructure has to be duplicated or all existing ones have to be updated.
To facilitate this work, AWS has developed CloudFormation which allows you to model and configure almost any AWS resource based on a YAML file. It also has an interface to track the progress of creation/modification operations.
Thanks to a ChangeSet system, you can see the modifications that will be applied to your resources to reach the state described by your YAML.

However, if you manually modify a resource, CloudFormation will not know about it and will undo the modification at the next update.

Thanks to CloudFormation our infrastructure is also versioned and it takes us about 30min to deploy an infrastructure identical to production in any region.

Solr

Solr being a weak point of our legacy infrastructure, we chose to move to Cloud mode. This mode requires adding Zookeeper, 3 in our case to be tolerant to the 1 zookeeper error.

Our first attempt was to run it on Fargate with 8GB of Ram and 4 vCpu and an EFS mount. The point of EFS was to run Solr nodes on any availability zone.

After a few weeks, the limits in terms of resources are quickly reached. The bigger your index is, the more RAM Solr needs, otherwise it will overexploit the file system and the indexing phases will go from a few minutes to several hours.

So we migrated to ECS. ECS is a lower layer than Fargate since you have to manage your EC2s yourself and make them available to Fargate to use. With 16GB of RAM, Solr is much more comfortable, but another limitation will kick in and drastically reduce performance.

EFS worked very well with Solr, we achieved very good read/write performance and it doesn't cost much. But what you have to know is that when you create a new file system on EFS, this system has a bandwidth of 100 MB/sec up to 2TB of data transfer. This is called Burst credits. If you exceed the 1MB/sec of bandwidth, you consume these credits and when there are more, you are capped at 1MB/sec. That's when Solr's performance goes down. So we switched to EBS and there, no more problems. The only constraint of EBS is that once the volume is created, it can't change zone. Solr needs to always run across the same availability zone.

Fastly

This is the service that will undergo the fewest changes in our new infrastructure.
However, a paywall system will be added to it in order to use the user's rights to vary the cache. The principle is that, for each HTTP request, Fastly will first query the backend to ask for the user's authorizations in order to add information, by different headers, to the original request. This information can be used as a cache variation key by Fastly.

Integration / Continuous Deployment

To update our application, we used all the tools provided by AWS, no external tools.

The diagram below shows you an overview of the different steps starting with the update of the Git branch to the update of the servers. 

Diagram of the stages of implementation of the new Docker infrastructure

1. Versioning

The developer chooses to deploy a feature on a particular instance. Each instance has its own corresponding GIT branch, so it’s enough to update this branch to trigger a deployment.

In addition to the production and staging instances we have several test instances (variable number depending on the needs) on which we can test a functionality in an isolated way as close as possible to the production.

We have 3 GIT repositories for the application, Docker containers and CloudFormation. A commit on an instance branch of the application or CloudFormation repository starts a pipeline on CodePipeline.

2. CodePipeline

Each instance has its own pipeline, so we can trigger several pipelines at the same time and thus update several instances at the same time. Each pipeline listens to a particular branch on 2 of our GIT repositories, the application and CloudFormation. As soon as a new commit arrives on one of the repositories the pipeline starts.

3. Build the Source container

The first step in the pipeline is to rebuild the "source" container, the one that contains the source code of the application and that will be shared with the other containers.

CodePipeline will therefore start a build, with CodeBuild, which will download the latest version of the sources from CodeCommit and execute the build steps. These build steps are described in a Dockerfile since the final result will be a Docker image. We will use Yarn and Composer to download and compile the PHP and Javascript dependencies.

The result will be a Docker image, based on Alpine, with all the compiled JS and PHP files, with a weight of 200Mb. This image will be sent to a private Docker repository, thanks to AWS ECR. And very important, the image will be tagged with the commit number corresponding to the sources. We'll see later what it will be used for.

4. Build of other containers

The next step is to build the other images. These are built from a separate Git repository in which we put all the Dockerfile.

Unlike the "source" container, it is not the latest version of the repository that is used, but the one mentioned in the application's composer.json file. This allows us to make sure that the application version will work with the right version of the other containers. This constraint is especially useful for the App and Worker containers so that they have the right configurations to run the PHP application.

This repository undergoes few modifications, so the Docker images are usually already existing. This step only takes a few seconds.

5. Deployment configuration

This step consists in downloading the application deployment templates in order to update the versions of the Docker images to be deployed.
CodeBuild will receive from CodePipeline the commit number given in the composer.json of the application to be deployed. Thanks to this commit number, it will get the digests of the images tagged with the same commit number. These digests will be added to the CloudFormation YAML files to reference the correct versions of the Docker images to be deployed. Once modified and compiled, these files will be dropped on an S3 for execution.

6. CloudFormation

Now that the configuration files are accessible on an S3, CodePipeline will ask CloudFormation to apply this configuration change.
CloudFormation will detect a change in the container digests and will therefore ask CodeDeploy to perform a new deployment. But this deployment will not be able to start until an administrator has given a final approval from the CodePipeline interface.

7. Deployment

CodeDeploy makes it possible to simplify container upgrades without service interruption. This is called Blue/Green deployment. CodeDeploy will first start the new containers ( Green ). Once started, it will modify the LoadBalancer to assign a port (of your choice, 4443 for example) to these new containers. At this stage, all requests arriving on port 4443 of the LoadBalancer will be returned by the new containers. The "old" containers (Blue) continue to receive traffic from port 443.

Now, CodeDeploy goes to the test phase and will run all the tests you have configured. Thanks to the port 4443 opened on the new containers, we can use a crawler that scans the whole site for errors.

Once the test phase is complete and no errors are detected, CodeDeploy will modify the LoadBalancer to redirect all traffic from port 443 to the new containers. Our new Green containers will turn Blue, and CodeDeploy will turn off the old containers. CodeDeploy can be configured to forward all traffic at once or in stages.

If an error occurs during this test phase, the LoadBalancer is reset to its initial state and the new containers are switched off.

Tips

After several months of work and pitfalls, here are some tips that could save you time.

Tags

By default, AWS does not require you to give a name to all the resources you create and AWS will randomly generate them. Often it will be prefixed by the name you gave to your CloudFormation stack used to create the resource. This can make your dashboard difficult to read, especially if you have a lot of resources displayed.

So you have the possibility to determine a name for your resource. However, in some cases, when the update of the resource requires its replacement (AWS will first create the new resource before deleting the old one), you will get an error as 2 resources can't have the same name.

In this case, the easiest way is to use tags, which do not need to be unique. There are several advantages to using tags. Most interfaces allow you to display them, or even to filter by tags. The AWS CLI also allows you to filter by tags.

Managing the rights assigned to your resources is much easier with tags than with resource names. To simplify tagging, when you use CloudFormation, tags given to a stack will be propagated to all resources managed by that stack.

And last but not least, AWS allows you to see the costs per tag, so you know which environment is costing you the most.

AWS CDK

We didn't use AWS CDK, but after several months of using Cloud Formation, we quickly reached the limits of the tool. Since it is based on yaml files, it quickly becomes difficult to do complex things, even if it is only to do conditions or loops. We end up using lambdas to do what can’t be done with yaml. CDK acts as an overlay to Cloud Formation, but allows us to declare our resources with languages like TypeScript or Python. It can also be used with Terraform. Maybe in a few months we will consider switching to CDK.

Healthcheck

When it comes to resiliency or scalability, healthcheck becomes a must. When you use AWS load balancer services, all of them have the possibility to set up health checks on the exploited resources. In our case, the health checks are done on our web servers, in order to be able to start them on demand in case of heavy load or to replace them if they do not respond.

In the case of a web service, the health checks are HTTP requests, just like the requests that the web server is supposed to handle. This means that at regular intervals, the Load Balancer will send an HTTP request to the web server and wait for it to respond.

In our case, the health check request will be transmitted by Nginx to PHP FPM, so it is a PHP script that will answer. PHP is configured to have a single pool, and it is the process manager that takes care of distributing the requests, arriving on this pool, between several PHP processes. Each pool listens to a dedicated port or socket from which the requests will arrive. If more requests arrive than the number of processes capable of handling them, then they are put on hold until a space becomes available.

Problems occur when too many requests arrive and are queued and health check requests are part of this. If PHP takes longer to respond to requests than the health check timeout configured by the Load Balancer, the server is considered unavailable. And if it fails to respond to several health check requests, the server will be replaced and the rest of the traffic switched to other servers. As the replacement of a server is not instantaneous, the other servers will increase in load and a cascade of unavailability will be reached.

On a progressive load increase, the auto scaling will have increased the number of servers accordingly to avoid this case. But our load tests revealed this particular case.

In order to avoid this situation, it is sufficient to declare a second pool in PHP FPM, which will listen to a particular port, and which will be in charge of answering only to the requests of Health check. And even in case of heavy load, these requests will be treated in priority.

DNS alias 

Instead of sending your web server the DNS of your Redis server, create an Alias in Route 53 of this Redis server, and configure your web server to use this Alias.

If one day you need to replace your Redis server, you will just have to replace this Alias in Route53 so that your web server takes it into account, without needing to restart it.

Signal management

With Fargate, when a container has to be switched off, it receives 2 signals. The first SIGTERM, and 2 minutes later SIGKILL. These signals are sent to notify of a shutdown and allow a container to be properly shut down before it is forced to shut down.

Most programs understand these signals, but sometimes do not react to them.

For this scenario there is a dumb-init which allows to convert the signals into a function of the program. For example, for PHP FPM, SIGTERM means an immediate stop, and SIGQUIT a soft stop.

So we will use the following instruction, in our docker entrypoint, to convert the SIGTERM (15) signal sent by Fargate into SIGQUIT(3):

Instruction to convert the SIGTERM signal to SIGQUIT

It will tell PHP to wait for the end of the execution of the requests being processed instead of abruptly interrupting them.

Chamber

Let's talk about security. The transmission of sensitive configuration data such as API keys, database passwords, OAuth certificates or private keys, needs special attention. Symfony does offer a solution, but it has some drawbacks that made us choose another solution: chamber. 

Chamber is a small tool for managing secrets from different secret storage services, AWS SSM Parameter Store in our case. We use it to save all the secrets used by our servers.

Example with the following line that does a cache flush by injecting as an environment variable, all the secrets configured for the "app/prod" environment in AWS SSM.

Secret chamber injection

The advantage of this launch mode is that secrets do not need to be defined in a bashrc or passed on at the launch of the docker container, so they will not be visible by other processes. Chamber can therefore be used as a prefix for the commands defined in entrypoint of your containers.

Conclusion

Switching to Docker forced us to rethink our entire infrastructure and the way we work. This step required a big investment, but the results are already visible. No more remote development servers, no more big servers sleeping and no more differences between production and development environments.
We are now up to date on the technologies and can easily anticipate our future needs. And each developer has more autonomy, provided they learn to work with Docker.

On the teamwork side, the DDD and the hexagonal architecture impose a way of coding and thinking that limits friction between the different functionalities and keeps a coherence in the way of developing.

All of this with the user's experience and satisfaction as the goal.

您可能感兴趣的其他文章

What are the 3 types of weakly supervised learning?

Supervised learning models have achieved robust performance across a wide range of tasks and domains. Nonetheless, they require a considerable amount of data preparation, particularly labeling, since they presuppose that each piece of data has an associated label.

Sarah Madeleine

Normalization, zero centering and standardization of CT images

In computer vision, three methods can be used to normalize the distribution of the dataset to speed up the training time of a neural network and gain good generalization in inference: normalization, zero centering, and standardization. Here are some examples of normalization with the TorchIO library.