当在Docker中使用Apify和Puppeteer时,遇到root用户的问题是很常见的。Puppeteer要求使用非特权用户来运行,以提高安全性。以下是解决这个问题的步骤和代码示例:
apifyuser
:FROM apify/actor-node-basic
# Create a new user
RUN groupadd -r apifyuser && useradd -r -g apifyuser -G audio,video apifyuser \
&& mkdir -p /home/apifyuser/Downloads \
&& chown -R apifyuser:apifyuser /home/apifyuser
# Set the user to apifyuser
USER apifyuser
# Set the working directory
WORKDIR /home/apifyuser/app
# Copy the package.json and package-lock.json files
COPY package*.json ./
# Install the dependencies
RUN npm ci --only=production
# Copy the rest of the application files
COPY . .
# Start the application
CMD [ "npm", "start" ]
docker run
命令中添加--user
参数,指定非特权用户的UID和GID。例如:docker run --user 1001:1001 my-apify-app
puppeteer
库时,需要指定--no-sandbox
和--disable-setuid-sandbox
选项,以便在非特权用户下正常运行。例如:const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch({
args: [
'--no-sandbox',
'--disable-setuid-sandbox'
]
});
const page = await browser.newPage();
// 进行其他操作
await browser.close();
})();
通过以上步骤和代码示例,您可以在Docker中成功使用Apify和Puppeteer,并避免root用户的问题。