Skip to content

Instantly share code, notes, and snippets.

@jeanlescure
Last active September 2, 2023 07:43
Show Gist options
  • Save jeanlescure/4fdedf770510241f9e7e07f942dba404 to your computer and use it in GitHub Desktop.
Save jeanlescure/4fdedf770510241f9e7e07f942dba404 to your computer and use it in GitHub Desktop.
How to setup an EC2 instance to run Chrome Headless for usage with Puppeteer

Chrome Headless on EC2

For puppeteer usage

How to setup an EC2 instance to run Chrome Headless for usage with Puppeteer

1. Spin up ubuntu EC2 instance and ssh into it

ssh ubuntu@ec2-3-21-123-234.compute-1.amazonaws.com

2. Install dependencies

sudo apt-get update
sudo apt-get install software-properties-common
sudo apt-get install gconf-service libxext6 libxfixes3 libxi6 libxrandr2 libxrender1 libcairo2 libcups2 libdbus-1-3 libexpat1 libfontconfig1 libgcc1 libgconf-2-4 libgdk-pixbuf2.0-0 libglib2.0-0 libgtk-3-0 libnspr4 libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 libx11-xcb1 libxcb1 libxcomposite1 libxcursor1 libxdamage1 libxss1 libxtst6 libappindicator1 libnss3 libasound2 libatk1.0-0 libc6 ca-certificates fonts-liberation lsb-release xdg-utils wget
wget https://www.googleapis.com/download/storage/v1/b/chromium-browser-snapshots/o/Linux_x64%2F650583%2Fchrome-linux.zip?alt=media -O chromium.zip
unzip chromium.zip

3. Run screen to be able to leave chrome open after exit

screen

4. Run headless chrome within screen

./chrome-linux/chrome --headless --remote-debugging-port=9222 --no-sandbox --disable-gpu --disable-dev-shm-usage --disk-cache-size=0 --remote-debugging-address=0.0.0.0

5. Detach and exit

Press ctrl+a then ctrl+d to detach from screen and exit ssh

NOTE: To re-attach to screen if necessary (to view logs or restart headless chrome) simply run:

screen -r

How to use in Puppeteer

NOTE: Make sure to install puppeteer-core so that the lambda instance does NOT download chrome.

  import puppeteer from 'puppeteer-core';

  const browser = await puppeteer.connect({
    'http://3.21.123.234:9222',
    defaultViewport: null
  });

  const page = await browser.newPage();

  const html = "<span>Some HTML</span>";

  await page.setContent(html, {waitUntil:['domcontentloaded', 'networkidle0']});
  await page.emulateMedia('print');

  const pdf = await page.pdf({
      "margin": {
        "top": ".5in",
        "right": ".5in",
        "bottom": "1in",
        "left": ".5in"
      },
      "format": "letter",
      "landscape": false
    });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment