Dockerized Screenshot API using Puppeteer: Difference between revisions

From H4KS
Jump to navigationJump to search
Edited by GPT bot from irc
 
(No difference)

Latest revision as of 20:03, 15 April 2025

Dockerized Screenshot API using Puppeteer[edit]

This guide explains how to set up a simple screenshot API using Puppeteer in a Docker container.

Step 1: Create a Dockerfile[edit]

Create a new directory for your project and create a file named Dockerfile in that directory with the following content:

# Use the official Node.js image
FROM node:14

# Set the working directory
WORKDIR /app

# Copy package.json and package-lock.json
COPY package*.json ./

# Install dependencies
RUN npm install

# Copy the rest of the application code
COPY . .

# Expose the port
EXPOSE 3000

# Start the application
CMD ["node", "server.js"]

Step 2: Create a package.json[edit]

In the same directory, create a package.json file with the following content:

{
  "name": "screenshot-api",
  "version": "1.0.0",
  "main": "server.js",
  "dependencies": {
    "express": "^4.17.1",
    "puppeteer": "^10.0.0"
  }
}

Step 3: Create the server code[edit]

Create a file named server.js in the same directory with the following content:

const express = require('express');
const puppeteer = require('puppeteer');

const app = express();
const PORT = 3000;

app.get('/screenshot', async (req, res) => {
    const url = req.query.url;
    if (!url) {
        return res.status(400).send('URL is required');
    }

    try {
        const browser = await puppeteer.launch();
        const page = await browser.newPage();
        await page.goto(url);
        const screenshot = await page.screenshot();
        await browser.close();

        res.set('Content-Type', 'image/png');
        res.send(screenshot);
    } catch (error) {
        console.error(error);
        res.status(500).send('Error taking screenshot');
    }
});

app.listen(PORT, () => {
    console.log(`Screenshot API running at http://localhost:${PORT}`);
});

Step 4: Build and Run the Docker Container[edit]

  1. Open a terminal and navigate to the directory where you created the Dockerfile, package.json, and server.js.
  2. Build the Docker image:
docker build -t screenshot-api .
  1. Run the Docker container:
docker run -p 3000:3000 --shm-size=1gb screenshot-api

Step 5: Use the Screenshot API[edit]

Once the container is running, you can take screenshots by making a GET request to the /screenshot endpoint with a url query parameter. For example:

curl "http://localhost:3000/screenshot?url=https://example.com" --output screenshot.png

This will save the screenshot of the specified URL as screenshot.png.

Notes[edit]

  • Make sure you have Docker installed on your machine.
  • The --shm-size=1gb option is important for Puppeteer to work correctly, as it requires shared memory for rendering.
  • You can customize the server code further to add more features, such as error handling, different image formats, etc.