index.md 26.3 KB
Newer Older
1
---
2
stage: Verify
3
group: Pipeline Execution
4
info: To determine the technical writer assigned to the Stage/Group associated with this page, see https://about.gitlab.com/handbook/engineering/ux/technical-writing/#assignments
5 6 7
disqus_identifier: 'https://docs.gitlab.com/ee/articles/laravel_with_gitlab_and_envoy/index.html'
author: Mehran Rasulian
author_gitlab: mehranrasulian
8
type: tutorial
9
date: 2017-08-31
10 11
---

12 13
<!-- vale off -->

14 15 16 17 18 19
# Test and deploy Laravel applications with GitLab CI/CD and Envoy

## Introduction

GitLab features our applications with Continuous Integration, and it is possible to easily deploy the new code changes to the production server whenever we want.

20
In this tutorial, we'll show you how to initialize a [Laravel](https://laravel.com) application and set up our [Envoy](https://laravel.com/docs/master/envoy) tasks, then we'll jump into see how to test and deploy it with [GitLab CI/CD](../README.md) via [Continuous Delivery](https://about.gitlab.com/blog/2016/08/05/continuous-integration-delivery-and-deployment-with-gitlab/).
21 22 23 24 25 26

We assume you have a basic experience with Laravel, Linux servers,
and you know how to use GitLab.

Laravel is a high quality web framework written in PHP.
It has a great community with a [fantastic documentation](https://laravel.com/docs).
Evan Read's avatar
Evan Read committed
27
Aside from the usual routing, controllers, requests, responses, views, and (blade) templates, out of the box Laravel provides plenty of additional services such as cache, events, localization, authentication, and many others.
28 29

We will use [Envoy](https://laravel.com/docs/master/envoy) as an SSH task runner based on PHP.
30
It uses a clean, minimal [Blade syntax](https://laravel.com/docs/master/blade) to set up tasks that can run on remote servers, such as, cloning your project from the repository, installing the Composer dependencies, and running [Artisan commands](https://laravel.com/docs/master/artisan).
31 32 33

## Initialize our Laravel app on GitLab

34
We assume [you have installed a new Laravel project](https://laravel.com/docs/master/installation#installation), so let's start with a unit test, and initialize Git for the project.
35 36 37

### Unit Test

38
Every new installation of Laravel (currently 8.0) comes with two type of tests, 'Feature' and 'Unit', placed in the tests directory.
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
Here's a unit test from `test/Unit/ExampleTest.php`:

```php
<?php

namespace Tests\Unit;

...

class ExampleTest extends TestCase
{
    public function testBasicTest()
    {
        $this->assertTrue(true);
    }
}
```

This test is as simple as asserting that the given value is true.

Laravel uses `PHPUnit` for tests by default.
If we run `vendor/bin/phpunit` we should see the green output:

62
```shell
63 64 65 66 67 68 69 70 71
vendor/bin/phpunit
OK (1 test, 1 assertions)
```

This test will be used later for continuously testing our app with GitLab CI/CD.

### Push to GitLab

Since we have our app up and running locally, it's time to push the codebase to our remote repository.
72
Let's create [a new project](../../../user/project/working_with_projects.md#create-a-project) in GitLab named `laravel-sample`.
73 74
After that, follow the command line instructions displayed on the project's homepage to initiate the repository on our machine and push the first commit.

75
```shell
76 77 78 79 80
cd laravel-sample
git init
git remote add origin git@gitlab.example.com:<USERNAME>/laravel-sample.git
git add .
git commit -m 'Initial Commit'
81
git push -u origin main
82 83 84 85 86
```

## Configure the production server

Before we begin setting up Envoy and GitLab CI/CD, let's quickly make sure the production server is ready for deployment.
Evan Read's avatar
Evan Read committed
87
We have installed LEMP stack which stands for Linux, NGINX, MySQL, and PHP on our Ubuntu 16.04.
88 89 90 91

### Create a new user

Let's now create a new user that will be used to deploy our website and give it
92
the needed permissions using [Linux ACL](https://serversforhackers.com/c/linux-acls):
93

94
```shell
95 96 97 98 99 100 101 102
# Create user deployer
sudo adduser deployer
# Give the read-write-execute permissions to deployer user for directory /var/www
sudo setfacl -R -m u:deployer:rwx /var/www
```

If you don't have ACL installed on your Ubuntu server, use this command to install it:

103
```shell
104 105 106 107 108 109 110 111 112
sudo apt install acl
```

### Add SSH key

Let's suppose we want to deploy our app to the production server from a private repository on GitLab. First, we need to [generate a new SSH key pair **with no passphrase**](../../../ssh/README.md) for the deployer user.

After that, we need to copy the private key, which will be used to connect to our server as the deployer user with SSH, to be able to automate our deployment process:

113
```shell
114 115 116 117 118 119 120 121
# As the deployer user on server
#
# Copy the content of public key to authorized_keys
cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys
# Copy the private key text block
cat ~/.ssh/id_rsa
```

122
Now, let's add it to your GitLab project as a [CI/CD variable](../../variables/README.md).
123
Project CI/CD variables are user-defined variables and are stored out of `.gitlab-ci.yml`, for security purposes.
124 125 126 127 128
They can be added per project by navigating to the project's **Settings** > **CI/CD**.

To the field **KEY**, add the name `SSH_PRIVATE_KEY`, and to the **VALUE** field, paste the private key you've copied earlier.
We'll use this variable in the `.gitlab-ci.yml` later, to easily connect to our remote server as the deployer user without entering its password.

129 130
![variables page](img/variables_page.png)

131
We also need to add the public key to **Project** > **Settings** > **Repository** as a [Deploy Key](../../../user/project/deploy_keys/index.md), which gives us the ability to access our repository from the server through [SSH protocol](../../../gitlab-basics/command-line-commands.md#start-working-on-your-project).
132

133
```shell
134 135 136 137 138 139 140 141
# As the deployer user on the server
#
# Copy the public key
cat ~/.ssh/id_rsa.pub
```

To the field **Title**, add any name you want, and paste the public key into the **Key** field.

142 143
![deploy keys page](img/deploy_keys_page.png)

144 145
Now, let's clone our repository on the server just to make sure the `deployer` user has access to the repository.

146
```shell
147 148 149 150 151 152 153 154
# As the deployer user on server
#
git clone git@gitlab.example.com:<USERNAME>/laravel-sample.git
```

Answer **yes** if asked `Are you sure you want to continue connecting (yes/no)?`.
It adds GitLab.com to the known hosts.

155
### Configuring NGINX
156 157 158

Now, let's make sure our web server configuration points to the `current/public` rather than `public`.

159
Open the default NGINX server block configuration file by typing:
160

161
```shell
162 163 164 165 166
sudo nano /etc/nginx/sites-available/default
```

The configuration should be like this.

167
```nginx
168 169 170 171 172 173 174 175 176 177 178 179 180 181
server {
    root /var/www/app/current/public;
    server_name example.com;
    # Rest of the configuration
}
```

You may replace the app's name in `/var/www/app/current/public` with the folder name of your application.

## Setting up Envoy

So we have our Laravel app ready for production.
The next thing is to use Envoy to perform the deploy.

182
To use Envoy, we should first install it on our local machine [using the given instructions by Laravel](https://laravel.com/docs/master/envoy/#introduction).
183 184 185 186 187 188 189 190 191

### How Envoy works

The pros of Envoy is that it doesn't require Blade engine, it just uses Blade syntax to define tasks.
To start, we create an `Envoy.blade.php` in the root of our app with a simple task to test Envoy.

```php
@servers(['web' => 'remote_username@remote_host'])

192
@task('list', ['on' => 'web'])
193 194 195 196
    ls -l
@endtask
```

Evan Read's avatar
Evan Read committed
197
As you may expect, we have an array within `@servers` directive at the top of the file, which contains a key named `web` with a value of the server's address (for example, `deployer@192.168.1.1`).
198 199 200 201
Then within our `@task` directive we define the bash commands that should be run on the server when the task is executed.

On the local machine use the `run` command to run Envoy tasks.

202
```shell
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
envoy run list
```

It should execute the `list` task we defined earlier, which connects to the server and lists directory contents.

Envoy is not a dependency of Laravel, therefore you can use it for any PHP application.

### Zero downtime deployment

Every time we deploy to the production server, Envoy downloads the latest release of our app from GitLab repository and replace it with preview's release.
Envoy does this without any [downtime](https://en.wikipedia.org/wiki/Downtime),
so we don't have to worry during the deployment while someone might be reviewing the site.
Our deployment plan is to clone the latest release from GitLab repository, install the Composer dependencies and finally, activate the new release.

#### @setup directive

219
The first step of our deployment process is to define a set of variables within [@setup](https://laravel.com/docs/master/envoy/#setup) directive.
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
You may change the `app` to your application's name:

```php
...

@setup
    $repository = 'git@gitlab.example.com:<USERNAME>/laravel-sample.git';
    $releases_dir = '/var/www/app/releases';
    $app_dir = '/var/www/app';
    $release = date('YmdHis');
    $new_release_dir = $releases_dir .'/'. $release;
@endsetup

...
```

- `$repository` is the address of our repository
- `$releases_dir` directory is where we deploy the app
- `$app_dir` is the actual location of the app that is live on the server
- `$release` contains a date, so every time that we deploy a new release of our app, we get a new folder with the current date as name
- `$new_release_dir` is the full path of the new release which is used just to make the tasks cleaner

#### @story directive

244
The [@story](https://laravel.com/docs/master/envoy/#stories) directive allows us define a list of tasks that can be run as a single task.
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
Here we have three tasks called `clone_repository`, `run_composer`, `update_symlinks`. These variables are usable to making our task's codes more cleaner:

```php
...

@story('deploy')
    clone_repository
    run_composer
    update_symlinks
@endstory

...
```

Let's create these three tasks one by one.

#### Clone the repository

263
The first task will create the `releases` directory (if it doesn't exist), and then clone the `main` branch of the repository (by default) into the new release directory, given by the `$new_release_dir` variable.
264 265 266 267 268 269 270 271 272
The `releases` directory will hold all our deployments:

```php
...

@task('clone_repository')
    echo 'Cloning repository'
    [ -d {{ $releases_dir }} ] || mkdir {{ $releases_dir }}
    git clone --depth 1 {{ $repository }} {{ $new_release_dir }}
Aris Lacdao's avatar
Aris Lacdao committed
273
    cd {{ $new_release_dir }}
274
    git reset --hard {{ $commit }}
275 276 277 278 279
@endtask

...
```

280
While our project grows, its Git history will be very long over time.
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
Since we are creating a directory per release, it might not be necessary to have the history of the project downloaded for each release.
The `--depth 1` option is a great solution which saves systems time and disk space as well.

#### Installing dependencies with Composer

As you may know, this task just navigates to the new release directory and runs Composer to install the application dependencies:

```php
...

@task('run_composer')
    echo "Starting deployment ({{ $release }})"
    cd {{ $new_release_dir }}
    composer install --prefer-dist --no-scripts -q -o
@endtask

...
```

#### Activate new release

Next thing to do after preparing the requirements of our new release, is to remove the storage directory from it and to create two symbolic links to point the application's `storage` directory and `.env` file to the new release.
Then, we need to create another symbolic link to the new release with the name of `current` placed in the app directory.
The `current` symbolic link always points to the latest release of our app:

```php
...

@task('update_symlinks')
    echo "Linking storage directory"
    rm -rf {{ $new_release_dir }}/storage
    ln -nfs {{ $app_dir }}/storage {{ $new_release_dir }}/storage

    echo 'Linking .env file'
    ln -nfs {{ $app_dir }}/.env {{ $new_release_dir }}/.env

    echo 'Linking current release'
    ln -nfs {{ $new_release_dir }} {{ $app_dir }}/current
@endtask
```

As you see, we use `-nfs` as an option for `ln` command, which says that the `storage`, `.env` and `current` no longer points to the preview's release and will point them to the new release by force (`f` from `-nfs` means force), which is the case when we are doing multiple deployments.

### Full script

The script is ready, but make sure to change the `deployer@192.168.1.1` to your server and also change `/var/www/app` with the directory you want to deploy your app.

At the end, our `Envoy.blade.php` file will look like this:

```php
@servers(['web' => 'deployer@192.168.1.1'])

@setup
    $repository = 'git@gitlab.example.com:<USERNAME>/laravel-sample.git';
    $releases_dir = '/var/www/app/releases';
    $app_dir = '/var/www/app';
    $release = date('YmdHis');
    $new_release_dir = $releases_dir .'/'. $release;
@endsetup

@story('deploy')
    clone_repository
    run_composer
    update_symlinks
@endstory

@task('clone_repository')
    echo 'Cloning repository'
    [ -d {{ $releases_dir }} ] || mkdir {{ $releases_dir }}
    git clone --depth 1 {{ $repository }} {{ $new_release_dir }}
Aris Lacdao's avatar
Aris Lacdao committed
351
    cd {{ $new_release_dir }}
352
    git reset --hard {{ $commit }}
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
@endtask

@task('run_composer')
    echo "Starting deployment ({{ $release }})"
    cd {{ $new_release_dir }}
    composer install --prefer-dist --no-scripts -q -o
@endtask

@task('update_symlinks')
    echo "Linking storage directory"
    rm -rf {{ $new_release_dir }}/storage
    ln -nfs {{ $app_dir }}/storage {{ $new_release_dir }}/storage

    echo 'Linking .env file'
    ln -nfs {{ $app_dir }}/.env {{ $new_release_dir }}/.env

    echo 'Linking current release'
    ln -nfs {{ $new_release_dir }} {{ $app_dir }}/current
@endtask
```

One more thing we should do before any deployment is to manually copy our application `storage` folder to the `/var/www/app` directory on the server for the first time.
You might want to create another Envoy task to do that for you.
376
We also create the `.env` file in the same path to set up our production environment variables for Laravel.
377 378
These are persistent data and will be shared to every new release.

379
Now, we would need to deploy our app by running `envoy run deploy`, but it won't be necessary since GitLab can handle that for us with CI's [environments](../../environments/index.md), which will be described [later](#setting-up-gitlab-cicd) in this tutorial.
380

381 382
Now it's time to commit [Envoy.blade.php](https://gitlab.com/mehranrasulian/laravel-sample/blob/master/Envoy.blade.php) and push it to the `main` branch.
To keep things simple, we commit directly to `main`, without using [feature-branches](../../../topics/gitlab_flow.md#github-flow-as-a-simpler-alternative) since collaboration is beyond the scope of this tutorial.
383 384
In a real world project, teams may use [Issue Tracker](../../../user/project/issues/index.md) and [Merge Requests](../../../user/project/merge_requests/index.md) to move their code across branches:

385
```shell
386 387
git add Envoy.blade.php
git commit -m 'Add Envoy'
388
git push origin main
389 390 391 392 393
```

## Continuous Integration with GitLab

We have our app ready on GitLab, and we also can deploy it manually.
394
But let's take a step forward to do it automatically with [Continuous Delivery](https://about.gitlab.com/blog/2016/08/05/continuous-integration-delivery-and-deployment-with-gitlab/#continuous-delivery) method.
395 396
We need to check every commit with a set of automated tests to become aware of issues at the earliest, and then, we can deploy to the target environment if we are happy with the result of the tests.

397
[GitLab CI/CD](../../README.md) allows us to use [Docker](https://www.docker.com) engine to handle the process of testing and deploying our app.
398
In case you're not familiar with Docker, refer to [Set up automated builds](https://docs.docker.com/get-started/).
399 400 401

To be able to build, test, and deploy our app with GitLab CI/CD, we need to prepare our work environment.
To do that, we'll use a Docker image which has the minimum requirements that a Laravel app needs to run.
402
[There are other ways](../php.md#test-php-projects-using-the-docker-executor) to do that as well, but they may lead our builds run slowly, which is not what we want when there are faster options to use.
403 404 405 406 407

### Create a Container Image

Let's create a [Dockerfile](https://gitlab.com/mehranrasulian/laravel-sample/blob/master/Dockerfile) in the root directory of our app with the following content:

408
```shell
409
# Set the base image for subsequent instructions
410
FROM php:7.4
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425

# Update packages
RUN apt-get update

# Install PHP and composer dependencies
RUN apt-get install -qq git curl libmcrypt-dev libjpeg-dev libpng-dev libfreetype6-dev libbz2-dev

# Clear out the local repository of retrieved package files
RUN apt-get clean

# Install needed extensions
# Here you can install any other extension that you need during the test and deployment process
RUN docker-php-ext-install mcrypt pdo_mysql zip

# Install Composer
426
RUN curl --silent --show-error "https://getcomposer.org/installer" | php -- --install-dir=/usr/local/bin --filename=composer
427 428 429 430 431

# Install Laravel Envoy
RUN composer global require "laravel/envoy=~1.0"
```

432
We added the [official PHP 7.4 Docker image](https://hub.docker.com/_/php), which consist of a minimum installation of Debian buster with PHP pre-installed, and works perfectly for our use case.
433 434 435 436 437

We used `docker-php-ext-install` (provided by the official PHP Docker image) to install the PHP extensions we need.

#### Setting Up GitLab Container Registry

438
Now that we have our `Dockerfile` let's build and push it to our [GitLab Container Registry](../../../user/packages/container_registry/index.md).
439 440 441 442 443 444 445

> The registry is the place to store and tag images for later use. Developers may want to maintain their own registry for private, company images, or for throw-away images used only in testing. Using GitLab Container Registry means you don't need to set up and administer yet another service or use a public registry.

On your GitLab project repository navigate to the **Registry** tab.

![container registry page empty image](img/container_registry_page_empty_image.png)

446
You may need to enable the Container Registry for your project to see this tab. You'll find it under your project's **Settings > General > Visibility, project features, permissions**.
447

448 449 450
To start using Container Registry on our machine, we first need to sign in to the GitLab registry using our GitLab username and password.
Make sure you have [Docker](https://docs.docker.com/engine/installation/) installed on our machine,
then run the following commands:
451

452
```shell
453 454
docker login registry.gitlab.com
```
455

456 457
Then we can build and push our image to GitLab:

458
```shell
459 460 461 462 463 464 465 466 467
docker build -t registry.gitlab.com/<USERNAME>/laravel-sample .

docker push registry.gitlab.com/<USERNAME>/laravel-sample
```

Congratulations! You just pushed the first Docker image to the GitLab Registry, and if you refresh the page you should be able to see it:

![container registry page with image](img/container_registry_page_with_image.jpg)

468
You can also [use GitLab CI/CD](https://about.gitlab.com/blog/2016/05/23/gitlab-container-registry/#use-with-gitlab-ci) to build and push your Docker images, rather than doing that on your machine.
469 470 471 472 473

We'll use this image further down in the `.gitlab-ci.yml` configuration file to handle the process of testing and deploying our app.

Let's commit the `Dockerfile` file.

474
```shell
475 476
git add Dockerfile
git commit -m 'Add Dockerfile'
477
git push origin main
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519
```

### Setting up GitLab CI/CD

In order to build and test our app with GitLab CI/CD, we need a file called `.gitlab-ci.yml` in our repository's root. It is similar to Circle CI and Travis CI, but built-in GitLab.

Our `.gitlab-ci.yml` file will look like this:

```yaml
image: registry.gitlab.com/<USERNAME>/laravel-sample:latest

services:
  - mysql:5.7

variables:
  MYSQL_DATABASE: homestead
  MYSQL_ROOT_PASSWORD: secret
  DB_HOST: mysql
  DB_USERNAME: root

stages:
  - test
  - deploy

unit_test:
  stage: test
  script:
    - cp .env.example .env
    - composer install
    - php artisan key:generate
    - php artisan migrate
    - vendor/bin/phpunit

deploy_production:
  stage: deploy
  script:
    - 'which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )'
    - eval $(ssh-agent -s)
    - ssh-add <(echo "$SSH_PRIVATE_KEY")
    - mkdir -p ~/.ssh
    - '[[ -f /.dockerenv ]] && echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config'

520
    - ~/.composer/vendor/bin/envoy run deploy --commit="$CI_COMMIT_SHA"
521 522 523 524 525
  environment:
    name: production
    url: http://192.168.1.1
  when: manual
  only:
526
    - main
527 528 529 530 531 532
```

That's a lot to take in, isn't it? Let's run through it step by step.

#### Image and Services

533 534
[Runners](../../runners/README.md) run the script defined by `.gitlab-ci.yml`.
The `image` keyword tells the runners which image to use.
535
The `services` keyword defines additional images [that are linked to the main image](../../services/index.md).
536 537 538 539 540 541 542 543 544 545 546
Here we use the container image we created before as our main image and also use MySQL 5.7 as a service.

```yaml
image: registry.gitlab.com/<USERNAME>/laravel-sample:latest

services:
  - mysql:5.7

...
```

Marcel Amirault's avatar
Marcel Amirault committed
547
If you wish to test your app with different PHP versions and [database management systems](../../services/index.md), you can define different `image` and `services` keywords for each test job.
548

549
#### CI/CD variables
550

551
GitLab CI/CD allows us to use [CI/CD variables](../../yaml/README.md#variables) in our jobs.
552 553 554
We defined MySQL as our database management system, which comes with a superuser root created by default.

So we should adjust the configuration of MySQL instance by defining `MYSQL_DATABASE` variable as our database name and `MYSQL_ROOT_PASSWORD` variable as the password of `root`.
555
Find out more about MySQL variables at the [official MySQL Docker Image](https://hub.docker.com/_/mysql).
556 557

Also set the variables `DB_HOST` to `mysql` and `DB_USERNAME` to `root`, which are Laravel specific variables.
558
We define `DB_HOST` as `mysql` instead of `127.0.0.1`, as we use MySQL Docker image as a service which [is linked to the main Docker image](../../services/index.md#how-services-are-linked-to-the-job).
559 560 561 562 563 564 565 566 567 568 569

```yaml
variables:
  MYSQL_DATABASE: homestead
  MYSQL_ROOT_PASSWORD: secret
  DB_HOST: mysql
  DB_USERNAME: root
```

#### Unit Test as the first job

570
We defined the required shell scripts as an array of the [script](../../yaml/README.md#script) keyword to be executed when running `unit_test` job.
571 572 573 574 575 576 577 578

These scripts are some Artisan commands to prepare the Laravel, and, at the end of the script, we'll run the tests by `PHPUnit`.

```yaml
unit_test:
  script:
    # Install app dependencies
    - composer install
579
    # Set up .env
580 581 582 583 584 585 586 587 588 589 590 591
    - cp .env.example .env
    # Generate an environment key
    - php artisan key:generate
    # Run migrations
    - php artisan migrate
    # Run tests
    - vendor/bin/phpunit
```

#### Deploy to production

The job `deploy_production` will deploy the app to the production server.
Marcel Amirault's avatar
Marcel Amirault committed
592
To deploy our app with Envoy, we had to set up the `$SSH_PRIVATE_KEY` variable as an [SSH private key](../../ssh_keys/index.md#ssh-keys-when-using-the-docker-executor).
593 594
If the SSH keys have added successfully, we can run Envoy.

595
As mentioned before, GitLab supports [Continuous Delivery](https://about.gitlab.com/blog/2016/08/05/continuous-integration-delivery-and-deployment-with-gitlab/#continuous-delivery) methods as well.
596 597
The [environment](../../yaml/README.md#environment) keyword tells GitLab that this job deploys to the `production` environment.
The `url` keyword is used to generate a link to our application on the GitLab Environments page.
598
The `only` keyword tells GitLab CI/CD that the job should be executed only when the pipeline is building the `main` branch.
599 600 601 602 603
Lastly, `when: manual` is used to turn the job from running automatically to a manual action.

```yaml
deploy_production:
  script:
604
    # Add the private SSH key to the build environment
605 606 607 608 609 610 611 612 613 614 615 616 617 618
    - 'which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )'
    - eval $(ssh-agent -s)
    - ssh-add <(echo "$SSH_PRIVATE_KEY")
    - mkdir -p ~/.ssh
    - '[[ -f /.dockerenv ]] && echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config'

    # Run Envoy
    - ~/.composer/vendor/bin/envoy run deploy

  environment:
    name: production
    url: http://192.168.1.1
  when: manual
  only:
619
    - main
620 621
```

ngaskill's avatar
ngaskill committed
622
You may also want to add another job for [staging environment](https://about.gitlab.com/blog/2021/02/05/ci-deployment-and-environments/), to final test your application before deploying to production.
623 624 625 626

### Turn on GitLab CI/CD

We have prepared everything we need to test and deploy our app with GitLab CI/CD.
627
To do that, commit and push `.gitlab-ci.yml` to the `main` branch. It will trigger a pipeline, which you can watch live under your project's **Pipelines**.
628 629 630 631 632

![pipelines page](img/pipelines_page.png)

Here we see our **Test** and **Deploy** stages.
The **Test** stage has the `unit_test` build running.
633
click on it to see the runner's output.
634 635 636 637 638 639 640

![pipeline page](img/pipeline_page.png)

After our code passed through the pipeline successfully, we can deploy to our production server by clicking the **play** button on the right side.

![pipelines page deploy button](img/pipelines_page_deploy_button.png)

641
After the deploy pipeline passed successfully, navigate to **Pipelines > Environments**.
642 643 644 645 646 647 648 649 650 651

![environments page](img/environments_page.png)

If something doesn't work as expected, you can roll back to the latest working version of your app.

![environment page](img/environment_page.png)

By clicking on the external link icon specified on the right side, GitLab opens the production website.
Our deployment successfully was done and we can see the application is live.

652
![Laravel welcome page](img/laravel_welcome_page.png)
653 654 655 656 657 658 659 660 661 662 663 664 665 666

In the case that you're interested to know how is the application directory structure on the production server after deployment, here are three directories named `current`, `releases` and `storage`.
As you know, the `current` directory is a symbolic link that points to the latest release.
The `.env` file consists of our Laravel environment variables.

![production server app directory](img/production_server_app_directory.png)

If you navigate to the `current` directory, you should see the application's content.
As you see, the `.env` is pointing to the `/var/www/app/.env` file and also `storage` is pointing to the `/var/www/app/storage/` directory.

![production server current directory](img/production_server_current_directory.png)

## Conclusion

Marcel Amirault's avatar
Marcel Amirault committed
667
We configured GitLab CI/CD to perform automated tests and used the method of [Continuous Delivery](https://continuousdelivery.com/) to deploy to production a Laravel application with Envoy, directly from the codebase.
668 669

Envoy also was a great match to help us deploy the application without writing our custom bash script and doing Linux magics.