This will make sure we have all requirements ready. Next, we want to run composer install to fetch all PHP dependencies and npm install to load Node.js packages, then run the npm script. We need to append them into before_script section:

In this particular case, the npm deploy script is a Gulp script that does the following:

Compile CSS & JS

Create sprites

Copy various assets (images, fonts) around

Replace some strings

All these operations will put all files into a build folder, which is ready to be deployed to a live server.

How to transfer files to a live server

You have multiple options: rsync, scp, sftp, and so on. For now, we will use scp.

To make this work, you need to add a GitLab CI/CD Variable (accessible on gitlab.example/your-project-name/variables). That variable will be called STAGING_PRIVATE_KEY and it's the private SSH key of your server.

Security tip

Create a user that has access only to the folder that needs to be updated.

After you create that variable, you need to make sure that key will be added to the Docker container on run:

only:dev means that this build will run only when something is pushed to the dev branch. You can remove this block completely and have everything be ran on every push (but probably this is something you don't want)

ssh-add ... we will add that private key you added on the web UI to the docker container

We will connect via ssh and create a new _tmp folder

We will connect via scp and upload the build folder (which was generated by a npm script) to our previously created _tmp folder

We will connect again via ssh and move the live folder to an _old folder, then move _tmp to live.

We connect to SSH and remove the _old folder

What's the deal with the artifacts? We just tell GitLab CI/CD to keep the build directory (later on, you can download that as needed).

Why we do it this way

If you're using this only for stage server, you could do this in two steps: