• Automation
  • Home
  • /
  • Learning Hub
  • /
  • Cypress Docker Tutorial: A Step-by-Step Guide
  • -
  • April 18 2023

Cypress Docker Tutorial: A Step-by-Step Guide

This Cypress Docker tutorial will help you learn how to simplify and streamline your testing process with Cypress and Docker.

OVERVIEW

Automation testing and Continuous Integration (CI) have become essential components of the development and testing process in today's software development process.

As a result, the use of Docker in CI/CD pipelines is becoming increasingly popular, as it allows for seamless integration of automation testing with the rest of the development workflow.

When combined with Cypress, it can further simplify the testing process. This means that automation engineers can use a Docker container that includes Cypress and all the necessary dependencies and use that container to run their automated tests in a consistent environment, regardless of where the tests are being run.

This Cypress Docker tutorial will help you learn how to simplify and streamline your testing process with Cypress and Docker. If you are preparing for an interview you can learn more through Cypress Interview Questions.

...

What is Docker?

Docker is an open-source software platform that uses OS-level virtualization and helps you create, deploy, and run applications securely using containers.

These containers are like virtual boxes that keep your software parts organized and separate from each other and add an extra layer of security.

Docker runs as a discrete process on the host machine, providing a stable and predictable environment for the application. Its flexibility allows it to be run on local machines that run Windows, Mac, or Linux, as well as on cloud infrastructure like AWS, Azure, and others. You can learn more about it through this blog on running tests in Docker.


cypress-docker-tutorial-img1

Docker has become the go-to DevOps platform for software engineers worldwide, providing a consistent, reliable testing experience. By using Cypress with Docker to run your tests, you can achieve several benefits.

  • Using Cypress with Docker provides a consistent environment across different machines and ensures that the tests run the same way every time. This is especially important when working in a team with different setups where everyone may have different OS and browser versions.
  • Using Cypress with Docker allows for faster and more efficient testing as it creates isolated environments for each test run. Finally, using Docker in your build pipeline ensures that your tests run smoothly and reliably, helping you to identify and fix issues early in the development process.

Before we dive deep into the usage of Docker with Cypress, let’s understand the basics first.

What is Dockerfile?

A Dockerfile is a script containing a set of commands used to create a Docker image. It serves as a guide for Docker to build an image by providing a sequence of instructions. These instructions are executed to produce the final Docker image.

Using a Dockerfile allows automation engineers to define and automate the steps required to create a Docker image, which can then be used to deploy the application in a containerized environment.

By using a Dockerfile to create a Docker image, you can easily set up a reproducible environment for running your tests. You can also easily share the Docker image with other automation engineers to ensure that everyone is running the tests in the same environment.

While doing automation, it's very common to encounter scenarios where a test case works flawlessly on one system but fails to perform as expected on another employee's system. These discrepancies can cause confusion and delay. However, by utilizing a Dockerfile, these situations can be easily avoided.

A Dockerfile allows automation engineers to create a container that includes all the necessary dependencies and libraries needed to run a software application. This means that automation engineers can create an environment consistent across all machines and avoid dependency issues that might cause tests to fail on one system but not another.


cypress-docker-tutorial-img2

Sample Dockerfile

What is Docker Image?

A Docker image is a snapshot of a container created by building a Dockerfile. It can be an existing image created by someone else or a new image created by you. Essentially, it is a lightweight, standalone, and executable package that includes all of the dependencies, configuration files, and application code needed to run your application.

Docker image contains all the necessary dependencies, such as Library, Configuration files, and Code. It is a read-only template that includes instructions for creating a Docker container. It can be created from scratch or based on an existing image. Docker images are stored in a Docker registry such as Docker Hub, a public repository of Docker images.

To create a Docker image, a Dockerfile can be used to define the instructions for building the image. Once the Dockerfile is created, the docker build command can be used to build the Docker image. The resulting image can then be pushed to a Docker registry, such as Docker Hub, for others to use.

Overall, Docker image is a self-contained package that includes everything needed to run an application, and it is created by building a Dockerfile using the docker build command.

Below are the Cypress Docker images available as of April 2023:


cypress-docker-tutorial-img3
...

What are Containers in Docker?

A Docker container is a live execution of a Docker image. It is an enclosed environment that bundles code and all its dependencies into a single, portable package. It is a lightweight and self-contained entity that comprises everything required to run an application.

At the application level, containers serve as an abstraction, completely unaware of the host's operating system or files. Instead, they leverage the environment provided by Docker Desktop, which includes a base operating system and all the dependencies needed to execute the application.

Containers are engineered to be lightweight, with all the essential components required to run an application, eliminating any dependencies on pre-existing software on the host machine. Multiple containers can run on the same machine and share the operating system kernel with other containers, each running as isolated processes in user space.

They are easy to share while you work, and you can be sure that everyone you share with gets the same container that works in the same way. This makes it easy to test applications across different environments.

Advantages of Docker

Docker is a popular containerization platform that offers several advantages, including:

Portability

Docker containers can run on cross-platform, including software engineers' laptops, data centers, and public clouds. This means that automation engineers can build and test applications locally and then deploy them seamlessly to the CI/CD pipeline.

Scalability

Because Docker containers are lightweight and run in isolation, they can be easily replicated and scaled up or down as needed to meet changing demands. This makes it easier to manage infrastructure resources efficiently and cost-effectively.

Security

Docker containers provide a high level of security and reliability as each container runs in its isolated environment, which helps prevent conflicts between applications and services.

Efficiency

Docker containers are lightweight and consume fewer resources than traditional virtual machines, making them more efficient. This allows software engineers to run multiple containers on a single host without any performance degradation.

Consistency

Docker containers provide a consistent environment for applications, ensuring that they run the same way across different systems, regardless of the underlying infrastructure. This ensures that the application behaves the same way in all environments.

Why use Docker for Cypress?

Using Docker with Cypress for end-to-end testing is a great way to ensure consistent and reliable testing results. By packaging your tests and their dependencies into a Docker container, you can easily move your tests between environments, run tests in parallel, and deploy tests to the cloud while performing Cypress end-to-end testing.

Below are some reasons why using Docker with Cypress can be beneficial:

Isolation

By running Cypress in a Docker container, you can ensure that your test environment is completely isolated from the host machine and any other dependencies like Node.js, Cypress and specific browser versions.

This means that even if you don't have Node.js or a specific browser version installed on your computer, you can still run the Cypress test case using the Cypress Docker image to ensure that your tests behave the same way on all machines. This prevents conflicts and ensures that tests are run in a consistent environment every time.

Using Docker, you don’t need to rely on the dependency to run the Cypress test. For example, if you want to run a test on Cypress version 12.9.0 and Chrome version 111.0.5563.146 but don’t have the same Cypress version and browser version available on your system. In that case, you can simply use pre-built Cypress- Docker image cypress-12.9.0-node-18.14.1-chrome-111.0.5563.146-1-ff-111.0.1-edge-111.0.1661.54-1, which has the respective Cypress version and Chrome browser available. This makes it easy to migrate your tests between machines and environments without worrying about installation or cross-platform issues.

Reproducibility

Docker allows you to create a consistent testing environment that can be easily reproduced across multiple operating systems. This helps ensure that your tests behave consistently, regardless of the operating system they are run on.

​​One of the primary benefits of using Docker for test automation is that it helps avoid common issues that can arise when executing tests across different systems. For example, you may experience problems when a test suite runs smoothly on your local machine but fails on your colleague's machine due to differences in browser version, Cypress version, and other factors.

Consider a scenario where you are running tests on Cypress version 12.0, but your colleague is still using an older version, such as Cypress version 9. In this situation, certain configurations may not work on their machine since Cypress version 9 and version 12.0 have different folder structures. However, Docker image can come to your rescue by ensuring that your tests are executed in a consistent and reproducible environment, regardless of the underlying system.

Portability

With Docker, you can easily move your Cypress tests and their dependencies between different machines and environments without worrying about setting up and configuring the environment each time.

Scalability

In addition to enabling the creation of a consistent testing environment, Docker makes it easy to run multiple instances of Cypress tests in parallel on the same machine or across multiple machines. There are pre-configured Cypress Docker images available in the Docker Hub registry. This Cypress Docker image contains all the dependencies and configurations required to run Cypress tests in a Docker container, making it easier to create a consistent testing environment across different systems.

Docker provides the capability to run multiple instances of Cypress tests in parallel on a single machine or across multiple machines.

This is made possible by Docker images designed specifically for test automation. These images contain all the necessary dependencies and configurations required for executing tests and can be spun up quickly, thus allowing for the rapid execution of tests across multiple instances.

By leveraging Docker images for test automation, you can significantly accelerate the testing process and reduce the overall test execution time, leading to faster time-to-market and improved product quality. This can help speed up your testing process and reduce the overall test execution time.

Also, explore our comprehensive guide on test execution engines, gaining insights into their functionalities to elevate your testing workflow with automation.

Easy Deployment

By packaging your Cypress tests and their dependencies into a Docker container, you can easily deploy your tests to any Docker-compatible environment, such as a cloud service provider or a Kubernetes cluster, without having to worry about installation or configuration issues.

For example, if you plan to run your tests on a CI/CD platform like Jenkins, you may need to install Node.js on Jenkins. However, by utilizing the Cypress Docker image, you can avoid this requirement and simply use Docker commands in your Jenkins pipeline.

Incorporating the Cypress Docker image into your CI/CD pipeline is a hassle-free way to automate the testing process and expedite the feedback loop for code modifications. With this image, you can easily create numerous containers to run tests in parallel, decreasing the overall time for test execution and facilitating faster iterations.

"Streamline your software development and integration process with the LambdaTest Docker integration. Seamlessly incorporate software applications into your current workflows"

Downloading and Setting up Docker

To get started with Cypress Docker, you will need to install Docker on your machine. Below are the steps that can be followed to install and set up Docker.

Step 1: Go to the official Docker website and download it as per your OS (Windows/Mac/Linux).


cypress-docker-tutorial-img4

Step 2: Install Docker.

Step 3: Launch Docker by double-clicking on it.

Step 4: Verify Docker installation by going to the terminal (Mac machine)/command-prompt (Windows) and entering the command:


docker --version

If you see the Docker version message (like the one shown in the screenshot below), that means Docker is installed successfully on your system


cypress-docker-tutorial-img5

Step 5: After installing and verifying Docker on the machine, let's start Docker now. You can start by simply clicking on Docker. It will open the window like shown below:


cypress-docker-tutorial-img6

If you see the above window, that means Docker is ready to run containers.

Running headless Cypress tests locally using Docker Image

Downloading and running Cypres involves just 1 step (if you have Node.js installed), but what if you don’t have Node.js/Cypress installed on your machine? It can be a hassle to set up the necessary environment.

This is where Docker comes in handy, allowing you to run Cypress tests on your local machine with just one Docker command without worrying about installing Cypress and Node.js.

The Docker image contains both Cypress and OS dependencies, which can be used to run Cypress tests. As of writing this Cypress Docker tutorial, four images are provided for running Cypress in Docker.

In this section of this Cypress Docker tutorial, we will be using cypress/included (the latest version of cypress/included is 12.8.1 at the time of writing the Cypress Docker tutorial). This Docker image comes with all operating system dependencies, Cypress, and browsers like Chrome and Firefox installed globally)

There are multiple ways in which Cypress tests can be run in Docker containers. One of the ways is to run using the following command from the root of your project:


docker run -it -v $PWD:/e2e -w /e2e cypress/included:12.8.1

Here's how you can run Cypress tests using a Docker image. Let's understand with an example.

Test Scenario

Implementation


cypress-docker-tutorial-img7
describe("Automation using Cypress", () => {
    it("Login into web app , search for product and verify it", () => {
        cy.visit("https://ecommerce-playground.lambdatest.io/index.php?route=account/login");
        cy.get('[id="input-email"]').type("lambdatest.Cypress@disposable.com");
        cy.get('[id="input-password"]').type("Cypress123!!");
        cy.get('[type="submit"]').eq(0).click();
        cy.get('[name="search"]').eq(0).type("Macbook");
        cy.get('[type="submit"]').eq(0).click();
        cy.contains("Macbook");
    });
});
LambdaTest

Execution

Start the Docker and go to your Cypress project. Open the terminal and run the below command:


docker run -it -v $PWD:/e2e -w /e2e cypress/included:12.8.1

cypress-docker-tutorial-img8

File Walkthrough

The above command is useful for running Cypress tests in a containerized environment, with the option to mount the current working directory as a volume so that changes made on the host system are reflected inside the container.

  • docker runtells Docker to run a container.
  • -it specifies that the container should be run in interactive mode.
  • -v argumentsto Docker run are for creating storage space inside a container.
  • $PWDmounts the current working directory (represented by the "$PWD" variable).
  • Here, PWD refers to your Cypress project’s root directory.


    cypress-docker-tutorial-img9
  • ./e2emap current folder to /e2e inside the container.
  • -w /e2esets the working directory inside the container to "/e2e".
  • cypress/included:12.8.1 specifies the Docker image to use for the container. In this case, it's the ""cypress/included"image, which includes Cypress and other dependencies pre-installed at version 12.8.1.

To ensure consistency and avoid potential issues, it is advisable to use a particular image tag rather than relying on the default tag. This is because the default tag can change over time as new versions of the image are released. If you use the default tag, your application may inadvertently use a different version of the image than the one you intended, potentially causing compatibility issues or other problems.

By using a specific image tag, such as "cypress/included:12.8.1", you ensure that your application always uses the same version of the image. This can help to prevent unexpected behavior and make it easier to troubleshoot any issues that arise.

In addition, using a specific image tag also makes it easier to track changes and maintain consistency across your infrastructure. If you need to update your application to use a new version of the image, you can simply update the tag in your configuration rather than manually track and update the image version number.


cypress-docker-tutorial-img10

As shown in the screenshot, the system is attempting to locate the Cypress Docker image. It first checks if the image is already downloaded on your system. If it is not found, the system will attempt to download the image from Docker Hub


cypress-docker-tutorial-img11

As shown in the screenshot below, you can run your Cypress test with a single Docker command. It is important to note that by default, the Cypress test runs in the Electron browser in headless mode, but while running it in headed mode, you can choose any supported browser of your choice from the Cypress test runner screen.

You can also check the container status after running the command using the command:


docker ps -a

cypress-docker-tutorial-img12
cypress-docker-tutorial-img13
...

2M+ Devs and QAs rely on LambdaTest

Deliver immersive digital experiences with Next-Generation Mobile Apps and Cross Browser Testing Cloud

Running Cypress tests on Chrome and Firefox browsers using Docker Image

Running Cypress tests on specific browser versions can be necessary to ensure compatibility with the target environment. Different browsers like Firefox and Chrome may have varying feature sets and behaviors that can affect the test results.

By default, Cypress runs the tests on the Electron browser, but if you want to run Cypress tests on Chrome and Firefox browsers using a Docker image, then you can follow the below detailed steps.

We will use the same test case used in the last step to run the Cypress test using Docker. To run the Cypress test locally on your machine using the Docker image, use the below command:


docker run -it -v $PWD:/e2e -w /e2e cypress/included:12.8.1 --browser firefox

cypress-docker-tutorial-img14

By using the command provided above, the Cypress test will be carried out in headless mode on the Firefox browser, specifically using the version currently installed on the local machine. This will ensure that all e2e tests are executed seamlessly.

To run the test case on the Chrome browser, you just need to change the browser name in the same command.


docker run -it -v $PWD:/e2e -w /e2e cypress/included:12.8.1 --browser chrome

cypress-docker-tutorial-img15

By utilizing the command provided above, the Cypress e2e test will be executed in headless mode on the Chrome browser (on the version currently installed on the local machine).

In the next section of the Cypress Docker tutorial, we will learn how to run Cypress tests on specific browser versions.

Running Cypress tests on Chrome and Firefox browsers using Dockerfile

In addition to executing Cypress tests with the command mentioned earlier, Dockerfile can also be utilized for the same purpose. This approach offers several benefits, including the ability to pass custom scripts from the package.json file and run them with Dockerfile.

One of the primary advantages of using Dockerfile for Cypress testing is that it offers greater flexibility in terms of customization. For the scenario in this Cypress Docker tutorial, we will be using the cypress/factory Docker image, which Cypress recently released.

This image can be used with Docker args to generate a Docker container with specific versions of Node, Cypress, and browsers like Chrome, Firefox, and Edge. Using this Docker image, you can test multiple browser versions.

The same can be achieved using cypress/included as well, but here, we are opting to use cypress/factory as it is a newly released option from Cypress and is particularly well-suited for generating a customized Docker image.

Now, let’s create a Dockerfile and run a Cypress test on a specific version of Chrome and Firefox browsers.

Create a Dockerfile at the root of your project.


cypress-docker-tutorial-img16

Pass the below code in Dockerfile.


ARG CHROME_VERSION='107.0.5304.121-1'
ARG EDGE_VERSION='100.0.1185.29-1'
ARG FIREFOX_VERSION='107.0'


FROM cypress/factory


WORKDIR /app
COPY . .


RUN npm install --save-dev cypress
LambdaTest

After creating a Dockerfile, you need to build the Docker image using the command:


docker build -t cypress-test-browser

After building, you can now run the Cypress test in Docker using the below command:


docker run -it cypress-test-browser -b chrome

You can also pass the args in the Docker build command. In that case, just change the Dockerfile content as shown below. (just remove Args instructions in Dockerfile)


FROM cypress/factory




WORKDIR /app


COPY . .


RUN npm install --save-dev cypress

To build the above Dockerfile, use the command:


docker build . --build-arg CHROME_VERSION='107.0.5304.121-1' --build-arg EDGE_VERSION='100.0.1185.29-1' --build-arg FIREFOX_VERSION='107.0' -t cypress-test-browsers

above command initiates the build

The above command initiates the build process for a Docker image. The build command takes the Dockerfile in the current directory (specified by the dot "."), and uses the specified build arguments (--build-arg) to set the versions of Chrome, Edge, and Firefox to be installed in the container. The -t flag sets the name of the resulting Docker image as "cypress-test-browsers".

It will run your test on the specified Chrome and Firefox versions only. You can pass it in the command to run it on different versions. The exact version must be used; no wildcards or shorthands are supported. You can pass any stable version of Chrome and Firefox in Dockerfile.

To run the Cypress test using the above shared Dockerfile, you can use the below command:


docker run cypress-test-browsers npm run cypress-test-browsers -b chrome

container based on the previously built image

The above command runs a Docker container based on the previously built image "cypress-test-browsers". The "npm run cypress-test-browsers -b chrome" command is executed inside the container, which invokes Cypress to run tests in the Chrome browser.

To execute the tests on the Firefox browser, simply include the flag "-b firefox" in the command. This will cause the tests to run on the Firefox browser version specified in the build command.


this will cause the tests to run
browser version specified in the build

Running Cypress tests in headless mode using Dockerfile

Running Cypress tests with Docker can help catch and fix issues early in the development process, saving time and resources down the line. By enabling early detection and resolution of bugs, this approach can streamline the development process and deliver reliable software with greater speed and efficiency.

The last approach in this Cypress Docker tutorial was running a Cypress test in Docker on your local machine using a Docker command, but what if you want to use a customized script and run it using Docker? In that case, you can use Dockerfile.

There are two approaches for using Dockerfile in Cypress:

  • The first involves passing the command npx cypress run in the Dockerfile, which will run all test cases under the e2e folder.
  • The second method involves passing a script (created in package.json) in the Dockerfile. This can be advantageous when running tests based on tags or when a customized script has been created.

Below is a step-by-step guide to creating a Dockerfile from scratch and running the Cypress test cases using Dockerfile.

Step 1: Open up the Integrated Development Environment (IDE) of your choice, like Visual Studio Code, and go to the project directory. Once there, create a new file at the root level of your project directory and name it Dockerfile (without any file extension).


your-project-directory-and-name

Step 2: Add the below code to the Dockerfile.


this will cause the tests to

Let’s understand the commands used in the above Dockerfile.

  • FROM cypress/included:12.8.1: It sets the base image for the container as the Cypress included image version 12.8.1. This means that the container will be built on top of this image and will include all of the dependencies and configurations already present in the Cypress included image version 12.8.1. cypress/included:12.8.1 is the official Cypress Docker image.
  • WORKDIR /app: It sets the working directory for any subsequent commands to /app. This means that any following commands, such as "COPY", "RUN", or "CMD", will be performed within this directory.
  • One important detail to keep in mind is that if the specified directory ("/app" in this case) does not already exist, the "WORKDIR" instruction will create it. Additionally, any "COPY" or "ADD" commands that come after the "WORKDIR" instruction will be executed relative to the specified working directory. Here, we have passed the name as /app, but any name can be passed as directoryName.


  • COPY . .: It copies all the files from the current directory (where the Dockerfile is located) to the /app directory in the Docker image.
  • The first “.” refers to the source directory on the host machine, and the second “.” refers to the destination directory within the container.


  • RUN npm install: It installs the dependencies for the project using npm.
  • CMD ["npm", "run", "npx cypress run"]: It specifies the command that will be executed when a container is started from this image. It runs the cypress run command using npm.

After creating a Dockerfile, let’s explore the process of building a Dockerfile, pushing it to a registry, and then running it.

Building the Docker Image

To build the Docker image, navigate to the directory containing your Dockerfile and run the following command:


docker build -t <image_name>

For example:

docker build -t cypress_docker


on running the above command

On running the above command, you will see the building process just as shown in the screenshot below:


you will see the building process just

Once it is successfully built, there will be a successful message on the terminal (just as shown in the screenshot below):


there will be a successful message on the terminal

After the Docker image is built, you can verify by running the command:


docker images

now run the docker image after building

You can now run the Docker image after building it by using the following command:


docker run imagename:tagname 

For example:

docker run cypress_docker latest


docker run cypress docker latest latest
now run the docker image after building it by using
this will run all the test cases in headless mode

This will run all the test cases in headless mode (it will perform npx cypress run)

Running Cypress tests on multiple browsers using Docker Compose

The Docker Compose file is a YAML file that defines how Docker containers should be built, configured, and run as a single service or application. With the Docker Compose file, you can define multiple containers and their configuration in a single file, making it easier to manage and deploy complex Cypress testing environments

For example, a Docker Compose file can be used to set up multiple containers for running Cypress tests on different browsers, such as Chrome, Firefox, and Edge. Each container can be configured with the specific browser and version needed for the tests. This means that you can run the same tests across multiple browsers simultaneously, making it easier to identify browser-specific issues.

The advantage of using docker-compose.yml is that you can use a single file to run Cypress test cases on multiple browsers using a single command. When you run the docker-compose up command, it will spin up three separate containers - one for each browser - and run the Cypress tests in parallel within these containers.

Prerequisite:

Install Docker Desktop

Let’s follow the step-by-step process to run the test cases - LoginPage.js and HomePage.js on Chrome, Firefox, and Edge at the same time using a single file, we will use docker-compose.yml.

Create a file named docker-compose.yml at the root of your project, just like shown below:


the root of your project just

Add the content to docker-compose.yml.


add the content to docker compose yml

File Walkthrough

The above-shared file is a Docker Compose file for running Cypress tests on multiple browsers. It has three services, each of which uses the cypress/included Docker image version 12.8.1 to run Cypress tests in different browsers. The services are named cypress-chrome, cypress-firefox, and cypress-electron, respectively.

  • version: 'cypress-docker-v1': This line specifies the version of the Docker Compose file format to use. In this case, it is a custom version called cypress-docker-v1.
  • services: This section defines the services that will be run as part of the Docker Compose environment.

  •  cypress-chrome:
       image: cypress/included:12.8.1
       command: "--browser chrome"
       working_dir: /cypress
       volumes:
         - ./:/cypress

    section defines the services that will be run
  • This section defines the services that will be run as part of the Docker Compose environment.
  • This defines a service called cypress-chrome that runs the Cypress tests on Google Chrome. It uses the cypress/included:12.8.1 Docker image as the base image, which includes Cypress pre-installed.

    The command specifies that it should run in Chrome, and the working_dir sets the working directory to /cypress. Finally, the volumes section mounts the current directory (represented by ./) as a volume inside the container at the /cypress directory, allowing the container to access the Cypress tests.


     cypress-firefox:
       image: cypress/included:12.8.1
       command: "--browser firefox"
       working_dir: /cypress
       volumes:
         - ./:/cypress

    section defines the services that will be run
  • This is similar to the previous service but runs the Cypress tests on Firefox instead.

  •  cypress-electron:
       image: cypress/included:12.8.1
       working_dir: /cypress
       volumes:
         - ./:/cypress
  • This defines a service called cypress-electron that runs the Cypress tests on the Electron browser, which is included in the Cypress image. The command section is not specified, as Cypress will automatically use Electron as the default browser when no -browser option is specified.

Once you create docker-compose file, You can run it using the below command:


docker-compose up

that runs the Cypress tests on the
cypress image the command
section is not specified
cypress will automatically use electron

By running your test case in headless mode, you lose the chance to observe the execution process. However, with Cypress, you can preserve videos of the test case. Furthermore, if you run your test case using docker-compose up within a Docker container, you can still watch the videos.

To accomplish this, we define a volume in the docker-compose.yml file that maps data from the Docker container to a specified path. In this case, all the data is copied from the container to /cypress. As a result, the Cypress test execution video is transferred from the Docker container to the cypress/videos directory.

Once the test execution is complete, you can view the videos of the test execution, similar to the example below.


test case in headless mode you lose
all the data is copied from the container
the test execution is complete

Apart from checking videos, you can also view the test execution using VNC Viewer, a tool that allows you to view the graphical desktop of a remote machine.

Running Cypress tests on Cloud Grid using Dockerfile

Cypress automation on a cloud-based testing digital experience testing platform like LambdaTest helps you attain accelerated test execution as well as improved browser coverage while performing Cypress testing on over 50+ browsers and OS combinations. In addition, you can fasten the release cycle up to 10x with Cypress parallel testing.

Check our documentation to get started with Cypress testing on LambdaTest.

You can also visit the below Cypress tutorial to get started with Cypress automation.

Subscribe to our LambdaTest YouTube Channel to get the latest updates on tutorials around Selenium testing, Cypress testing, Appium, and more.

There are multiple ways to perform Cypress UI testing on a cloud testing platform like LambdaTest. One of them is using Docker.

Below is the Cypress end-to-end testing code, which we will run in the LambdaTest cloud platform.


describe("Automation using Cypress", () => {
    it("Login into web app , search for product and verify it", () => {
        cy.visit("https://ecommerce-playground.lambdatest.io/index.php?route=account/login");
        cy.get('[id="input-email"]').type("lambdatest.Cypress@disposable.com");
        cy.get('[id="input-password"]').type("Cypress123!!");
        cy.get('[type="submit"]').eq(0).click();
        cy.get('[name="search"]').eq(0).type("Macbook");
        cy.get('[type="submit"]').eq(0).click();
        cy.contains("Macbook");
    });
});
LambdaTest
end-to-end testing code

To run the Cypress tests on the LambdaTest Platform, we need to do the configuration using three steps.

Step 1: Install LambdaTest CLI.

Install LambdaTest CLI using npm by using the below command:


npm install lambdatest-cypress-cli

once the lambdatest cli is installed

Step 2: Set up the config.

Once the LambdaTest CLI is installed, we need to set up the configuration using the below command:


lambdatest-cypress init

we need to set up the configuration

After running the command, there will be a file created in your project named “lambdatest-config.json”. We need to set up the configuration to run our test case on different browsers on LambdaTest.

  • auth: We need to set up the LambdaTest credentials, which will be used in lambdatest-config.json to run my test case on the cloud platform.
  • browsers: Need to specify the browser and OS version on which we want our test case to run.
  • run_setting: Need to set up the config in run_settings. Set up the config name, which would differ based on different Cypress Versions, and set up the spec file.

For Cypress version 10 and above, you can follow the below code to set up lambdatest-config.json.


{
  "lambdatest_auth": {
     "username": "user.name",
     "access_key": "access.key"
  },
  "browsers": [
     {
        "browser": "Chrome",
        "platform": "Windows 10",
        "versions": [
           "latest-1"
        ]
     },
     {
        "browser": "Firefox",
        "platform": "Windows 10",
        "versions": [
           "latest-1"
        ]
     }
  ],
  "run_settings": {
     "config_file": "cypress.config.js",
     "reporter_config_file": "base_reporter_config.json",
     "build_name": "Cypress-Test",
     "parallels": 1,
     "specs": "./cypress/e2e/*.cy.js",
     "ignore_files": "",
     "network": false,
     "headless": false,
     "npm_dependencies": {
        "cypress": "12.7.0"
     }
  }}

Step 3: Execute test case.

Once the config is done, you can execute the Cypress test case on the LambdaTest Cypress Cloud. You just need to run the below command to run it on LambdaTest.


lambdatest-cypress run

lambdatest-cypress-run

After the command is run and test cases are executed successfully, you can view the Cypress test run on the LambdaTest cloud platform (as shown in the screenshot below):


lambdatest-cypress-run-view
cypress-test-with-docker

Until now, in this Cypress Docker tutorial, we learned how to perform Cypress UI automation on the LambdaTest cloud platform using the IDE terminal. Let’s see how to run the above flow using Cypress with Dockerfile.

To run it using Docker, we will use the Dockerfile in which you can pass the script, defined in package.json.

You need to create a script in package.json. To run the Cypress test on the LambdaTest cloud platform, we need to run the command “lambdatest-cypress run”.

The same command we will create as a script in package.json just as shown below:


{
"name": "cypress_withdocker",
"version": "1.0.0",
"description": "Cypress test using Docker",
"main": "index.js",
"scripts": {
"cypress-test-cloud": "lambdatest-cypress run"
},
"repository": {
"type": "git",
"url": "git+https://github.com/Anshita-Bhasin/Cypress_WithDocker.git"
},
"author": "Anshita Bhasin <anshita@propertyfinder.ae>",
"license": "ISC",
"bugs": {
"url": "https://github.com/Anshita-Bhasin/Cypress_WithDocker/issues"
},
"homepage": "https://github.com/Anshita-Bhasin/Cypress_WithDocker",
"dependencies": {
"cypress": "^12.9.0",
"lambdatest-cypress-cli": "^3.0.11"
}
} 

To test if the above script is working fine, Go to the terminal and execute the command:


<npm run scriptname> 

For the above code, the command would be npm run cypress-test-cloud. If you see the tests result just as shown below, your script is working fine.


npm-run-cypress-test-cloud

To run the same using Dockerfile, follow these steps:

  • Create a Dockerfile (at the root of the project, as shown in the last section of this Cypress Docker tutorial).
    docker-file
  • Pass the below code in Dockerfile.
  •  FROM cypress/included:12.8.1
    WORKDIR /app
    COPY . .
    RUN npm install
    ENTRYPOINT ["npm","run", "cypress:test:cloud"] 
    
    LambdaTest

File Walkthrough:

This Command runs the cypress command to execute the Cypress tests. It will check in package.json if there is a command with the name cypress-test-cloud, and then it will run, else it will throw an error.

  • FROM cypress/included:12.8.1: This line specifies the base image to use for building the Docker image. cypress/included:12.8.1 is a pre-built image that includes the Cypress automation tool and all its dependencies.
  • WORKDIR /app: This line sets the working directory for subsequent commands to /app. This is the directory where the code and any other files will be copied during the build process.
  • COPY . .: This line copies all files in the current directory (denoted by .) to the working directory in the Docker image (also denoted by .).
  • RUN npm install: This line runs the npm install command to install all required dependencies for the application.
  • ENTRYPOINT ["npm","run", "cypress:test:cloud"]: This line sets the default command to run when the Docker container starts. In this case, it runs the npm run cypress:test:cloud command, a defined script in package.json to run Cypress tests in the cloud.

After creating a Dockerfile, the next step is to build a Dockerfile to run it. Make sure to start the Docker before building it. Just open Docker Desktop on your machine, and you should be logged in.

Building the Docker image

To build the Docker image using this Dockerfile, you can run the following command in the directory containing the Dockerfile:


docker build -t <image_name> 

For example:

docker build -t cypress_example:v1


docker-build-cypress

On running the above command, you would see the building process just as shown in the screenshot below:


building-process

Once it is successfully built, there will be a successful message on the terminal that the build is FINISHED.

Once the Docker image is built, you can verify its presence by running the below command:


docker images 

This command lists all the Docker images currently available on your local machine.


docker-images

After building the Docker image, you can push it. However, you may encounter an access denied issue despite being logged in. In such a situation, you can resolve the problem by tagging the image and then pushing it. Before attempting to push, ensure that you have logged in by running the below command:


docker login 

docker-login

Tag the image using the below command:


docker tag imagename:tag dockerUsername/imagename:tag

For example:

docker tag cypress_example:v1 anshita1012/cypress_example:v1


docker-cypress-example

It is important to note username refers to your Docker Hub account username, which is used for logging into Docker Hub. You can find your Docker Hub account username by logging into Docker Desktop and looking at your profile information.


docker-profile-login

The next step is to push the docker image. This is used to upload a Docker image from your local machine to a Docker registry, such as Docker Hub or a private registry. Once an image is pushed to a registry, it can be downloaded and used by others, either for running containers or as a base image for building new images.

To push the docker image, you can use the below command:


docker push dockerUsername/image-name:v1

For example:

docker push anshita1012/:v1


docker-push

The above command will push the image named cypress_example with the tag v1 to a Docker registry under the account username (anshita1012).


cypress-example

This might take time if you are running it for the first time.

After the Docker image is built and pushed. The final step is to run the Docker image using the command:


docker run <image_name>:<tag_name> 

For example:

docker run cypress_example:v1


docker-run-cypress-example

As shown above, it is running the tests on a cloud platform using the Dockerfile. You can verify the Cypress test run on the LambdaTest cloud platform (as shown in the screenshot below):


docker-cloud-platform

So, following the above approach, you can run your Cypress tests on the cloud platform using Dockerfile on different browsers like Chrome and Firefox.

It is important to note once you have pushed your Docker image, any changes made afterward to the script will not be reflected in the image. To update the image with the latest changes, you must rebuild the image and push it again. Therefore, it is necessary to rebuild and push the Docker image each time you make changes to the script.

Running Cypress tests in Docker Container on CI/CD (GitHub Actions)

GitHub Actions is a powerful CI/CD platform that enables you to automate workflows for building, testing, and publishing software across multiple platforms, operating systems, and programming languages. With GitHub Actions, you can even see the status checks displayed within the pull request.

One of the significant advantages of using Cypress with GitHub Actions is that it allows you to execute Cypress tests in a Docker container, providing a self-contained and repeatable environment for testing.

Fortunately, there is an existing Docker image that already includes Chrome version 87 and Firefox version 82 pre-installed, which you can use to run Cypress tests. To leverage this image, you can pass the container image as an argument. Once the test cases are executed, the container is automatically stopped.

Below is a sample code to run Cypress tests in a Docker container using GitHub Actions:


name: Cypress Test in custom container
on: [push]
jobs:
cypress-test:
runs-on: ubuntu-22.04
name: Cypress Tests on docker container
# Cypress Docker image with Chrome v78
# and Firefox v70 pre-installed
container: cypress/browsers:node12.18.3-chrome87-ff82
steps:
- uses: actions/checkout@v3
- uses: cypress-io/github-action@v5
with:
browser: chrome
LambdaTest

The above code sets up a GitHub Actions workflow that triggers when a push event occurs. It then defines a job named cypress-test that runs on an Ubuntu 20.04 virtual machine.

The job specifies the Docker container image to use for running Cypress tests, which in this case is cypress/browsers:node12.13.0-chrome78-ff70.

The job also includes steps to check out the code repository using the actions/checkout@v3 action and to run Cypress tests using the cypress-io/github-action@v5 action.

The browser parameter is set to Chrome to specify that the tests should be run in the Chrome browser.

When you push your code, GitHub Actions will be executed, and you can view your result from the Actions tab.


docker-github-actions
cypress-tests-docker
cypress-tests-docker-container

Bonus: Top Docker Commands

Sharing some useful Docker commands.


CommandExplanation
docker build -t <image-name>Build Docker Image
docker pull <image-name>Pull Docker Image
docker push <image-name>:tag-name Push Docker Image
docker run -t <image-name> Run Docker Image
docker imagesShow all docker images
docker system prune -aStop all containers and delete all the images
docker kill <container-id>Kill docker container
docker run <imag_name>Start Docker
docker loginLogin In
docker ps -aList all running docker containers
docker stopStop container
docker logs containerIdView the logs
docker-compose upStart a group of containers defined in a Docker Compose file.

If you are a developer or a tester, the Cypress 101 certification from LambdaTest is a great way to learn Cypress and enhance your skills in test automation. It is designed for beginners and experienced developers and testers who want to learn the basics of Cypress and how to use it to write automated tests for web applications.

Conclusion

Docker makes it easy to build and run applications in containers, and Cypress makes it easy to write and execute tests in a browser. By combining these two tools, you can create a powerful testing environment that is reliable and efficient.

In this Cypress Docker tutorial, we have seen how using Cypress tests with Docker provides an efficient and reliable way to write and execute tests in a browser. By creating a Dockerfile with the necessary instructions for building a Docker image, you can easily build and run the image on both Chrome and Firefox browsers. The Docker container can also be easily deployed and scaled, making it a valuable tool for automated testing. With the powerful combination of Docker and Cypress, developers can ensure that their web applications are thoroughly tested and meet the desired quality standards. You can learn more about some tips & tricks through the hub on cypress tips and tricks.

Frequently asked questions

  • General ...
Can Cypress run in Docker?
Yes, Cypress can run in Docker. Running Cypress in Docker is a popular way to execute end-to-end tests in a containerized environment. To run Cypress in Docker, you need to create a Docker image that includes all the dependencies required to run Cypress, such as Node.js, npm, and any other packages your application relies on. You can use an existing Node.js image from Docker Hub as a base image and then install Cypress and your application's dependencies using npm.
What is Docker in Cypress?
Docker is a platform that enables developers to create, deploy, and run applications in containers. A container is a lightweight, standalone executable package that includes everything needed to run an application, including code, dependencies, libraries, and system tools. Docker provides a way to encapsulate an application and its dependencies into a container, which can then be easily deployed across different environments.In the context of Cypress, Docker is often used to run end-to-end tests in a containerized environment. Running Cypress in a Docker container provides several benefits, such as: Consistency, Isolation, Scalability, Portability

Did you find this page helpful?

Helpful

NotHelpful

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud