Running API Test in Docker
Running Postman API collections in Docker is a great way to automate your API tests in a consistent environment. This guide will walk you through the process of setting up and running Postman collections using Docker and Newman (the command-line companion for Postman).
Prerequisites
- Docker: Ensure Docker is installed on your machine. You can download it from the Docker website.
- Postman Collection: You should have a Postman collection (
.json
file) ready to run. You can export your collection from Postman by clicking on the collection, selecting "Export", and saving the file.
Step-by-Step Guide
Step 1: Create a Dockerfile
Create a new directory for your project and navigate to it. Inside this directory, create a file named Dockerfile
and add the following content:
# Use the official Node.js image as the base image
FROM node:18.8.0
# Set the working directory inside the container
WORKDIR /usr/src/app
# Install Newman globally
RUN npm install -g newman
# Copy the collection file into the container
COPY your-collection-file.json /usr/src/app/your-collection-file.json
# Copy the environment file into the container (if you have one)
COPY your-environment-file.json /usr/src/app/your-environment-file.json
# Command to run the Newman collection
CMD ["newman", "run", "your-collection-file.json", "-e", "your-environment-file.json"]
Replace your-collection-file.json
and your-environment-file.json
with the actual names of your collection and environment files.
Step 2: Build the Docker Image
Open a terminal, navigate to your project directory, and run the following command to build your Docker image:
docker build -t postman-collection-runner .
This command tells Docker to build an image from the Dockerfile in the current directory and tag it as postman-collection-runner
.
Step 3: Run the Docker Container
Once the image is built, you can run the container using the following command:
docker run --rm postman-collection-runner
This command runs the container and executes the Newman command to run your Postman collection. The --rm
flag ensures the container is removed after it finishes running.
Step 4: Generating Reports to app directory
Make sure there is reports folder in project directory
$(pwd)/reports
gets the absolute path of the current directory followed by /reports
on the host machine.
/reports
is the path where the volume will be mounted inside the container.api-latest
is assumed to be the correct image name. Replace it with the actual image name if it's different.
docker run -d -v "$(pwd)/reports:/reports" postman-collection-runner