CCNA Scripting Containers Questions

75 of 151 questions · Page 1/3 · Scripting Containers topic · Answers revealed

1
MCQmedium

An organization uses Kubernetes to deploy containerized applications. A pod fails to start with an ImagePullBackOff error. What is the most likely cause?

A.The pod exceeded its memory limit
B.The container port is already in use
C.The node is out of disk space
D.The image name is misspelled or does not exist in the registry
AnswerD

This is the most common cause of ImagePullBackOff.

Why this answer

The ImagePullBackOff error in Kubernetes indicates that the kubelet is unable to pull the container image from the specified registry. The most common cause is a misspelled image name or a non-existent image in the registry, which prevents the container runtime from fetching the image. This triggers a back-off mechanism where the kubelet retries the pull with increasing delays.

Exam trap

CompTIA often tests the distinction between ImagePullBackOff and CrashLoopBackOff, where candidates mistakenly attribute a pull failure to resource limits or port conflicts instead of recognizing it as a registry/image name issue.

How to eliminate wrong answers

Option A is wrong because exceeding the pod's memory limit causes an OOMKill (Out of Memory Kill) error, not ImagePullBackOff; the pod would be terminated with a CrashLoopBackOff or OOM status. Option B is wrong because a container port already in use results in a port conflict error during pod startup, typically manifesting as a 'port already allocated' or 'bind: address already in use' error, not an image pull failure. Option C is wrong because a node running out of disk space leads to an EvictionThreshold or ImageGCFailure, which may prevent pod scheduling or cause pod eviction, but the specific error for image pull failures due to disk space is usually 'ImagePullBackOff' only if the image cannot be downloaded, though the primary symptom of disk pressure is node-level eviction, not a registry-related pull error.

2
MCQmedium

A developer is writing a Bash script that must be portable across different Linux distributions. The script needs to check if a package is installed. Which command should be used to achieve this portability?

A.which package
B.command -v package
C.dpkg -l package
D.rpm -q package
AnswerB

POSIX-compliant.

Why this answer

The `command -v package` command is the most portable way to check if a package is installed across different Linux distributions because it uses the POSIX-standard `command` shell built-in, which works in any Bourne-compatible shell (bash, sh, dash, etc.) regardless of the underlying package manager. It returns the path to the executable if the package's binary is in the PATH, or nothing if it is not installed, making it distribution-agnostic.

Exam trap

The trap here is that candidates often choose `dpkg` or `rpm` because they are familiar with checking packages on their own distribution, but the question explicitly requires portability across different Linux distributions, making the distribution-agnostic `command -v` the correct choice.

How to eliminate wrong answers

Option A is wrong because `which package` is not a POSIX-standard command and its behavior can vary across distributions; it may not be installed by default or may produce different exit codes, reducing portability. Option C is wrong because `dpkg -l package` is specific to Debian-based distributions (e.g., Ubuntu) and will fail or be unavailable on Red Hat-based or other distributions. Option D is wrong because `rpm -q package` is specific to Red Hat-based distributions (e.g., CentOS, Fedora) and will not work on Debian-based or other package management systems.

3
MCQhard

After building and running the container as shown in the exhibit, the administrator tries to access http://localhost:8080 but receives a connection refused error. What is the most likely cause?

A.The container exited immediately after starting.
B.The port mapping is incorrect.
C.The base image is not compatible.
D.The CMD syntax is incorrect.
AnswerA

Check docker ps to see if running.

Why this answer

The most likely cause is that the container exited immediately after starting. When a container runs a command that finishes quickly (e.g., a shell script that exits), the container stops, and no process listens on port 8080. This results in a 'connection refused' error because the container is no longer running to accept connections.

Exam trap

CompTIA often tests the distinction between a container that fails to start (e.g., due to syntax errors) and one that starts but exits immediately, where the 'connection refused' error is a symptom of the latter.

How to eliminate wrong answers

Option B is wrong because if the port mapping were incorrect, the container would still be running but inaccessible on the specified host port; the error would be 'connection timeout' or 'no route to host', not 'connection refused'. Option C is wrong because an incompatible base image would cause a build failure or runtime crash, not a clean exit with a 'connection refused' error. Option D is wrong because incorrect CMD syntax would cause a build error or a container that fails to start, not one that runs and then exits immediately.

4
Multi-Selectmedium

Which TWO of the following are characteristics of containers compared to virtual machines? (Choose two.)

Select 2 answers
A.Containers run their own kernel.
B.Each container has its own operating system.
C.Containers use hypervisor for isolation.
D.Containers require less overhead than VMs.
E.Containers typically start in seconds.
AnswersD, E

No hypervisor, shares OS.

Why this answer

Option D is correct because containers share the host OS kernel and do not require a full guest OS per instance, resulting in significantly lower resource overhead (CPU, memory, and storage) compared to virtual machines. Option E is correct because containers are lightweight processes that can start in seconds, whereas VMs require booting an entire operating system, which typically takes minutes.

Exam trap

The trap here is that candidates often confuse container isolation with hypervisor-based isolation, mistakenly thinking containers run their own kernel or OS, when in fact they share the host kernel and use namespaces/cgroups.

5
MCQmedium

Refer to the exhibit. A developer is pushing an image to a private registry at `192.168.1.100:5000` but receives an error about using an insecure registry. Which part of the Docker daemon configuration allows this registry without TLS?

A.The 'insecure-registries' setting
B.The 'exec-opts' setting
C.The 'storage-driver' setting
D.The 'log-driver' setting
AnswerA

This setting explicitly allows insecure (non-TLS) connections to the specified registry.

Why this answer

The error indicates the Docker client is attempting to push an image to a registry over HTTP (port 5000) without TLS. By default, Docker Engine requires TLS for all registry communications. The `insecure-registries` setting in `/etc/docker/daemon.json` allows the daemon to bypass TLS verification for specified IP addresses or CIDR ranges, enabling communication with registries that lack a valid TLS certificate.

Exam trap

CompTIA often tests the distinction between daemon configuration options that affect registry communication versus those that affect container runtime or storage, leading candidates to confuse `insecure-registries` with unrelated settings like `exec-opts` or `storage-driver`.

How to eliminate wrong answers

Option B is wrong because `exec-opts` is used to pass options to the container runtime (e.g., native.cgroupdriver=systemd), not to configure registry security. Option C is wrong because `storage-driver` defines the storage backend (e.g., overlay2, aufs) for container layers, not registry TLS settings. Option D is wrong because `log-driver` configures the logging driver for containers (e.g., json-file, syslog), and has no role in registry TLS enforcement.

6
Multi-Selecteasy

A Linux administrator is creating a shell script to back up configuration files to a remote server. The script must ensure that if any command fails (e.g., rsync or tar), the script exits immediately and does not continue. Which TWO of the following should be included in the script to achieve this behavior? (Choose two.)

Select 2 answers
A.trap 'exit 1' ERR
B.set -o pipefail
C.set -x
D.set -e
E.set -u
AnswersA, D

Traps the ERR signal and exits when any command fails.

Why this answer

Option A is correct because `trap 'exit 1' ERR` instructs the shell to execute `exit 1` whenever a command returns a non-zero exit status, which immediately terminates the script on any failure. Option D is correct because `set -e` causes the shell to exit immediately if any command (or pipeline, unless overridden) fails, providing a straightforward way to enforce fail-fast behavior in a backup script.

Exam trap

The trap here is that candidates often confuse `set -o pipefail` with `set -e`, thinking it alone causes script exit, or they mistakenly believe `set -x` or `set -u` handle command failures, when in fact only `set -e` and `trap ... ERR` directly enforce exit on any non-zero exit status.

7
MCQmedium

Based on the exhibit, what is the most likely cause of the repeated connection refused errors?

A.The DNS resolution for the database host fails.
B.A firewall is blocking port 3306.
C.The database service is down.
D.The database credentials are incorrect.
AnswerC

Connection refused typically means no process listening.

Why this answer

The 'connection refused' error indicates that the client's TCP SYN packet reached the target host on port 3306, but the host actively rejected the connection because no process is listening on that port. This is the classic symptom of the MySQL/MariaDB database service being stopped or crashed, as the OS TCP stack sends an RST packet when a connection attempt hits a port with no listening socket.

Exam trap

CompTIA often tests the distinction between 'connection refused' (service down) and 'connection timeout' (firewall blocking) — candidates confuse the two because both prevent access, but the TCP error message uniquely identifies the cause.

How to eliminate wrong answers

Option A is wrong because DNS resolution failures would produce a 'Name or service not known' error, not a TCP-level 'connection refused'. Option B is wrong because a firewall blocking port 3306 would cause the connection to time out (no response) or be silently dropped, not produce an immediate 'connection refused' which requires a TCP RST from the target host. Option D is wrong because incorrect credentials result in an authentication failure after the TCP connection is established, typically returning 'Access denied for user' from the database server, not a transport-layer refusal.

8
MCQhard

A DevOps engineer is creating a Podman container that needs to communicate with a host service listening on a Unix socket at /run/host-service.sock. Which of the following mount options will make the socket available inside the container?

A.--device /run/host-service.sock:/run/host-service.sock
B.--bind /run/host-service.sock:/run/host-service.sock
C.--volume /run/host-service.sock:/run/host-service.sock
D.--mount type=bind,source=/run/host-service.sock,target=/run/host-service.sock
AnswerC

Correctly binds the host socket into the container.

Why this answer

Option C is correct because `--volume` in Podman (and Docker) can bind-mount a single file, such as a Unix socket, from the host into the container. This makes `/run/host-service.sock` available at the same path inside the container, allowing the containerized process to communicate with the host service over the socket.

Exam trap

The trap here is that candidates confuse `--device` (for hardware devices) with bind-mounting a socket file, or they misremember the exact syntax for `--mount`, which requires `type=bind` and comma-separated key=value pairs.

How to eliminate wrong answers

Option A is wrong because `--device` is used to expose host devices (e.g., `/dev/sda`) to a container, not regular files or sockets; it does not handle Unix socket bind mounts. Option B is wrong because `--bind` is not a valid Podman or Docker flag; the correct syntax for a bind mount uses `--volume`, `--mount`, or `-v`. Option D is wrong because the `--mount` flag requires a comma-separated list of key=value pairs (e.g., `type=bind,source=/run/host-service.sock,target=/run/host-service.sock`), but the given syntax is missing the `type=bind` key and uses incorrect formatting; it would be rejected by Podman.

9
MCQmedium

A junior administrator is writing a bash script that should exit immediately if any command in a pipeline fails. Which command should be added at the beginning of the script?

A.set -u
B.shopt -s extglob
C.set -e
D.set -o pipefail
AnswerD

Ensures pipeline fails on any component error.

Why this answer

Option D is correct because `set -o pipefail` ensures that if any command in a pipeline fails (returns a non-zero exit status), the entire pipeline is considered to have failed, and with `set -e` (which is often used alongside it), the script will exit immediately. This is specifically required by the question: 'exit immediately if any command in a pipeline fails.' Without `pipefail`, only the exit status of the last command in the pipeline is considered, so earlier failures would be ignored.

Exam trap

The trap here is that candidates often choose `set -e` (option C) thinking it covers all command failures, but they overlook that `set -e` does not propagate failures through pipelines unless `set -o pipefail` is also set, which is the specific requirement in the question.

How to eliminate wrong answers

Option A is wrong because `set -u` causes the script to exit when an unset variable is referenced, but it does nothing to handle pipeline failures or exit on command errors. Option B is wrong because `shopt -s extglob` enables extended pattern matching in bash (e.g., `?(pattern)`, `*(pattern)`), which is unrelated to error handling or pipeline exit behavior. Option C is wrong because `set -e` alone causes the script to exit on a command failure, but it does not apply to pipelines; by default, only the last command in a pipeline determines the exit status, so a failure in an earlier command would not trigger `set -e`.

10
MCQhard

An organization is migrating from a legacy automation tool to Ansible. Which of the following best describes the role of Ansible playbooks in configuration management?

A.YAML files that declare the desired state of systems and tasks to achieve it.
B.Executable scripts written in Python that run on managed nodes.
C.Configuration files that list the inventory of managed hosts.
D.Shell scripts that execute ad-hoc commands across servers.
AnswerA

Defines tasks and states declaratively.

Why this answer

Ansible playbooks are YAML files that declare the desired state of systems and the tasks to achieve that state, making them the core configuration management tool in Ansible. They are idempotent, meaning running them multiple times yields the same result, and they use modules to enforce configurations without requiring an agent on managed nodes.

Exam trap

The trap here is confusing playbooks with ad-hoc commands or inventory files, as candidates often think playbooks are scripts that execute directly on nodes rather than declarative YAML files that define desired state and tasks.

How to eliminate wrong answers

Option B is wrong because Ansible playbooks are not executable Python scripts; they are YAML declarative files that invoke Python modules on the control node, not scripts that run directly on managed nodes. Option C is wrong because inventory files, not playbooks, list managed hosts; playbooks define tasks and desired states. Option D is wrong because playbooks are not shell scripts; they are structured YAML files that orchestrate idempotent tasks, while ad-hoc commands are run via the `ansible` command, not playbooks.

11
MCQmedium

A company is deploying a new web application using Docker containers. The application requires configuration values that vary between environments (development, staging, production). Which approach ensures the configuration is securely managed and applied without modifying the container image?

A.Pass configuration via environment variables and use Docker secrets for sensitive data.
B.Build separate images for each environment with the configuration baked in.
C.Store configuration in a JSON file within the base image and override it at runtime.
D.Use a Dockerfile to copy the configuration file from the host at build time.
AnswerA

Environment variables allow runtime configuration without modifying the image, and secrets provide secure handling of sensitive data.

Why this answer

Option A is correct because Docker supports passing configuration via environment variables at runtime without altering the image, and Docker secrets securely manage sensitive data (e.g., passwords, API keys) by storing them in encrypted memory and mounting them as temporary files in `/run/secrets/`. This decouples configuration from the immutable image, adhering to the twelve-factor app methodology and ensuring environment-specific values are applied without rebuilding.

Exam trap

CompTIA often tests the misconception that environment variables alone are sufficient for all configuration, including secrets, but the trap here is that Docker secrets provide an additional security layer for sensitive data, while environment variables are appropriate for non-sensitive configuration values.

How to eliminate wrong answers

Option B is wrong because building separate images for each environment violates immutability and defeats the purpose of a single deployable artifact, leading to configuration drift and increased maintenance overhead. Option C is wrong because storing configuration in a JSON file within the base image requires modifying the image or using a bind mount at runtime, which either breaks immutability or relies on host filesystem access, not a secure or portable approach. Option D is wrong because using a Dockerfile to copy a configuration file from the host at build time bakes the configuration into the image, making it environment-specific and requiring separate builds for each environment, which is inefficient and insecure.

12
MCQmedium

A company runs a critical web application on a single server using Docker containers. The application consists of a web frontend container and a backend API container. Recently, the server ran out of disk space due to Docker logs and temporary images. The sysadmin is tasked with automating cleanup to prevent recurrence. The solution must not disrupt running containers. Which approach should be taken?

A.Increase disk space by adding a new volume.
B.Create a script that stops all containers, removes unused images, and restarts containers.
C.Schedule a cron job to run `docker system prune -a -f` daily.
D.Configure log rotation for containers using `--log-opt max-size=10m` and `--log-opt max-file=3` in the Docker run command, and schedule `docker image prune -f` weekly.
AnswerD

Log rotation keeps log files small, and pruning unused images safely removes them without affecting running containers.

Why this answer

Option D is correct because it addresses both root causes: log growth and dangling images. Configuring `--log-opt max-size=10m` and `--log-opt max-file=3` limits container log file size and count without stopping containers, while `docker image prune -f` removes unused images safely. This combination prevents disk exhaustion without disrupting running containers, meeting all requirements.

Exam trap

The trap here is that candidates may choose Option C because `docker system prune -a -f` seems like a comprehensive cleanup, but they overlook that it can remove images needed by running containers (if they use intermediate layers) and does not address log growth, which is the primary cause of disk space exhaustion in this scenario.

How to eliminate wrong answers

Option A is wrong because adding a new volume only postpones the problem by increasing capacity, but does not automate cleanup of logs or unused images, so disk space will eventually run out again. Option B is wrong because stopping all containers disrupts the critical web application, violating the requirement to not disrupt running containers. Option C is wrong because `docker system prune -a -f` removes all unused images, containers, networks, and volumes, including those that might be needed for running containers (e.g., intermediate layers), and it does not address log rotation, so logs will continue to grow unchecked.

13
MCQmedium

Refer to the exhibit. A Docker container using a bind mount fails to start with a permission error. What is the most likely cause?

A.The container is running in privileged mode.
B.The Docker daemon is not running as root.
C.SELinux is blocking the mount.
D.The volume path on the host does not exist.
AnswerC

SELinux policies can restrict bind mounts, resulting in permission denied errors.

Why this answer

When a Docker container uses a bind mount and fails with a permission error, SELinux is a common cause because it enforces mandatory access controls that can block container processes from accessing host files. By default, SELinux labels container processes with a confined domain (e.g., container_t), and if the bind-mounted host directory lacks the proper SELinux context (e.g., container_file_t), the mount is denied. This is resolved by adding the `:Z` or `:z` flag to the bind mount in the Docker run command to relabel the host directory appropriately.

Exam trap

CompTIA often tests the distinction between filesystem permission errors (e.g., user ID mismatch) and SELinux denials, where candidates mistakenly choose 'privileged mode' or 'daemon not root' because they overlook SELinux as the underlying cause in a bind mount context.

How to eliminate wrong answers

Option A is wrong because running the container in privileged mode grants all capabilities and bypasses most security restrictions, but it does not automatically resolve SELinux denials; in fact, privileged mode may still be blocked by SELinux unless SELinux is disabled or the context is set. Option B is wrong because the Docker daemon typically runs as root, and even if it did not, the permission error from a bind mount is more likely related to SELinux or filesystem permissions, not the daemon's user ID. Option D is wrong because if the volume path on the host did not exist, Docker would create it as a directory (unless a file is expected), and the error would be a 'no such file or directory' message, not a permission error.

14
Drag & Dropmedium

Drag and drop the steps to mount a new filesystem in the correct order.

Drag steps to the numbered slots on the right, or tap a step then tap a slot.

Steps
Order

Why this order

Mounting a filesystem requires creating a mount point and using the mount command with the device and mount point.

15
MCQmedium

A container is running a database service that requires persistent storage. The administrator wants to ensure that data persists even if the container is removed. Which volume mount type should be used in the Docker run command?

A.--mount type=volume
B.--mount type=bind
C.COPY in Dockerfile
D.--mount type=tmpfs
AnswerB

Bind mounts map a host directory, ensuring data persists.

Why this answer

Option B is correct because a bind mount directly maps a host directory into the container, ensuring that data written to that mount point persists on the host filesystem even after the container is removed. This is ideal for database services that require persistent storage independent of the container lifecycle.

Exam trap

The trap here is that candidates often confuse Docker volumes with bind mounts, assuming volumes are the only persistent option, but bind mounts also provide persistence and are the correct choice when the question explicitly requires a host directory mapping.

How to eliminate wrong answers

Option A is wrong because `--mount type=volume` creates a Docker-managed volume that persists data, but the question specifies the administrator wants data to persist even if the container is removed; while volumes also persist, the correct answer for the given scenario is bind mount, as the question implies a direct host path mapping. Option C is wrong because `COPY` in a Dockerfile only copies files into the image at build time, not at runtime, and does not provide persistent storage that survives container removal. Option D is wrong because `--mount type=tmpfs` mounts a temporary filesystem stored in memory, which is volatile and data is lost when the container stops or is removed.

16
MCQeasy

A DevOps engineer needs to run a container that executes a batch job and then exits. The container image is stored in a private registry. Which Docker command should be used to run the container and automatically remove it after it exits?

A.docker run --rm private.registry.com/batch:latest
B.docker start --rm private.registry.com/batch:latest
C.docker run -d private.registry.com/batch:latest
D.docker exec --rm private.registry.com/batch:latest
AnswerA

The --rm flag ensures the container is removed after it exits, and the image is pulled from the registry.

Why this answer

The `docker run --rm` command automatically removes the container after it exits, which is ideal for batch jobs that should not leave behind stopped containers. The image reference `private.registry.com/batch:latest` pulls from a private registry when not cached locally. This combination ensures the container runs once, completes its task, and is cleaned up without manual intervention.

Exam trap

CompTIA often tests the distinction between `docker run` (creates and starts a new container) and `docker start` (restarts an existing container), and the trap here is that candidates may confuse `--rm` as a generic cleanup flag applicable to any Docker command, when it is only valid with `docker run`.

How to eliminate wrong answers

Option B is wrong because `docker start` only starts an existing stopped container; it cannot pull or run a new image from a registry, and `--rm` is not a valid flag for `docker start`. Option C is wrong because `docker run -d` runs the container in detached mode (background) and does not automatically remove it after exit; the container would remain as a stopped container. Option D is wrong because `docker exec` runs a command inside an already running container, not a new container from an image, and `--rm` is not a valid flag for `docker exec`.

17
Multi-Selectmedium

Which TWO of the following are valid methods to pass environment variables to a Docker container at runtime?

Select 2 answers
A.Using the -e flag with docker run
B.Using the ENV instruction in the Dockerfile
C.Using the --environment flag with docker run
D.Using the --env-file flag with docker run
E.Using the --env flag with docker run
AnswersA, D

Valid runtime option.

Why this answer

Option A is correct because the `-e` flag (or `--env`) with `docker run` allows you to set environment variables directly on the command line, e.g., `docker run -e MY_VAR=value`. This is a standard and widely used method to pass environment variables at runtime without modifying the image.

Exam trap

CompTIA often tests the distinction between build-time (`ENV` in Dockerfile) and runtime (`-e` or `--env-file`) variable injection, and candidates may mistakenly think `--env-file` is invalid or that `--environment` is a real flag.

18
MCQmedium

A container named web2 exited with status 0. Which of the following is the most likely reason?

A.The container ran a task and completed
B.The container's entrypoint crashed
C.The container was stopped manually with docker stop
D.The container ran out of memory
AnswerC

docker stop sends SIGTERM, causing a clean exit with code 0.

Why this answer

Exit code 0 indicates a successful termination. When a container exits with status 0, it means the main process (entrypoint or command) completed its task without errors. Option C is correct because `docker stop` sends a SIGTERM signal to the container's PID 1, allowing it to shut down gracefully; if the process handles the signal and exits cleanly, the exit code will be 0.

Exam trap

The trap here is that candidates often assume exit code 0 always means the container completed its intended work, but Cisco tests the nuance that a manual `docker stop` can also produce exit code 0 if the process handles the shutdown gracefully.

How to eliminate wrong answers

Option A is wrong because while a container that runs a task and completes will also exit with status 0, the question states the container was 'stopped manually with docker stop', which is the most likely reason given the explicit action. Option B is wrong because if the container's entrypoint crashed, it would typically exit with a non-zero status (e.g., 1, 2, or 139 for a segfault), not 0. Option D is wrong because running out of memory causes the container to be killed by the OOM killer, which results in exit code 137 (128 + 9, where 9 is SIGKILL), not 0.

19
Multi-Selecthard

A security policy requires that containers run with minimal privileges. Which THREE measures should be implemented? (Select THREE.)

Select 3 answers
A.Use --security-opt seccomp=default
B.Mount host filesystem read-write
C.Run as non-root user
D.Expose all ports to host
E.Drop all Linux capabilities and add only required
AnswersA, C, E

The default seccomp profile restricts system calls, improving security.

Why this answer

Running as non-root, dropping capabilities, and using a default seccomp profile all reduce privileges. Mounting host filesystem read-write and exposing all ports increase risk.

20
MCQmedium

An administrator needs to deploy a containerized web application on a Linux server. The application requires port 8080 to be mapped to host port 80. Which command will run the container in detached mode with this port mapping?

A.docker run -p 80:8080 webapp
B.docker run -d -p 8080:80 webapp
C.docker run -d -p 8080:80 webapp
D.docker run -d -p 80:8080 webapp
AnswerD

Correctly maps host port 80 to container port 8080 in detached mode.

Why this answer

Option D is correct because the `-d` flag runs the container in detached mode, and `-p 80:8080` maps host port 80 to container port 8080, which matches the requirement. The syntax is `-p host_port:container_port`, so `-p 80:8080` correctly exposes the application's container port 8080 on the host's port 80.

Exam trap

The trap here is that candidates often confuse the order of port mapping in the `-p` flag, mistakenly thinking `-p container_port:host_port` is correct, when the correct syntax is `-p host_port:container_port`.

How to eliminate wrong answers

Option A is wrong because it omits the `-d` flag, so the container runs in the foreground (attached mode), not detached. Option B is wrong because it uses `-p 8080:80`, which maps host port 8080 to container port 80, reversing the required mapping (the application listens on container port 8080, not 80). Option C is identical to Option B and is wrong for the same reason: it incorrectly maps host port 8080 to container port 80.

21
MCQhard

A system administrator notices that a cron job runs every 5 minutes but should run only on weekdays. The current crontab entry is: */5 * * * * /usr/local/bin/script.sh. Which change to the time fields will restrict execution to Monday through Friday?

A.*/5 9-17 * * 1-5 /usr/local/bin/script.sh
B.*/5 * * * 1-6 /usr/local/bin/script.sh
C.*/5 * * * 1-5 /usr/local/bin/script.sh
D.5 * * * 1-5 /usr/local/bin/script.sh
AnswerC

Runs every 5 minutes, every hour, every day of month, every month, on weekdays (1-5).

Why this answer

Option C is correct because the fifth field in a crontab entry specifies the day of the week, where 1 represents Monday and 5 represents Friday. By setting this field to `1-5`, the cron job will only execute on weekdays, while the `*/5` in the minute field ensures it still runs every 5 minutes. The other fields remain as `*` to allow execution at any hour and any day of the month.

Exam trap

The trap here is that candidates may confuse the day-of-week field with the day-of-month field, or incorrectly assume that `1-5` excludes weekends without realizing that cron's day-of-week numbering starts with Sunday as 0, so `1-5` correctly maps to Monday-Friday.

How to eliminate wrong answers

Option A is wrong because it adds a range `9-17` in the hour field, which restricts execution to business hours (9 AM to 5 PM) instead of only weekdays, and this is not required by the question. Option B is wrong because it uses `1-6` for the day-of-week field, which includes Saturday (6) in addition to weekdays, causing the job to run on Saturdays as well. Option D is wrong because it changes the minute field from `*/5` to `5`, meaning the job would run only at minute 5 of every hour, not every 5 minutes, thus altering the frequency requirement.

22
MCQeasy

A junior administrator writes a bash script to check disk usage and send an email alert. The script runs manually but does not execute from cron. Which of the following is the most likely cause?

A.Script not marked executable
B.Incorrect file permissions on cron job
C.Missing shebang line
D.Absolute path not specified in crontab
AnswerD

Cron runs with a minimal PATH; without a full path to the script, the job will not find it.

Why this answer

When a script runs manually from the command line but fails from cron, the most common cause is that cron does not inherit the user's PATH environment. Without an absolute path to the script in the crontab entry, cron cannot locate the script. Option D directly addresses this: specifying the full path (e.g., /home/user/script.sh) ensures cron can find and execute it.

Exam trap

CompTIA often tests the misconception that cron failures are due to file permissions or missing shebangs, when the real issue is the restricted cron environment—specifically the lack of an absolute path or a missing PATH variable.

How to eliminate wrong answers

Option A is wrong because if the script were not marked executable, it would also fail when run manually from the command line (unless invoked with 'bash script.sh'), but the question states it runs manually. Option B is wrong because cron jobs themselves are not files with permissions; the cron table (crontab) is a configuration file, and its permissions (typically 600 owned by the user) are not the issue—the script's permissions or cron's environment are. Option C is wrong because a missing shebang line would cause the script to fail regardless of how it is invoked (manual or cron), but the script runs manually, so a shebang is present or the shell is explicitly specified.

23
MCQhard

A container needs to communicate with a database on the host machine using the default bridge network. The container cannot resolve the host by hostname. Which approach should be used?

A.Set --net=host
B.Use --link db:db
C.Create a custom bridge network
D.Use --add-host host.docker.internal:host-gateway
AnswerD

This adds a host entry that resolves to the host's IP via the gateway, allowing the container to reach host services.

Why this answer

Option D is correct because `--add-host host.docker.internal:host-gateway` adds a special entry to the container's `/etc/hosts` file that resolves `host.docker.internal` to the host machine's gateway IP address, which on the default bridge network is the host itself. This allows the container to reach the host by a consistent hostname without relying on Docker's internal DNS, which does not resolve hostnames on the default bridge. The `host-gateway` magic value automatically maps to the host's IP (typically 172.17.0.1 on Linux).

Exam trap

The trap here is that candidates often confuse `--net=host` as a quick fix for hostname resolution, not realizing it sacrifices network isolation and is not the intended method for reaching the host from a container on the default bridge.

How to eliminate wrong answers

Option A is wrong because `--net=host` removes network isolation entirely, making the container share the host's network stack, which is overly permissive and not a targeted solution for hostname resolution. Option B is wrong because `--link` is a legacy feature that provides name resolution between containers, not between a container and the host machine. Option C is wrong because creating a custom bridge network enables automatic DNS resolution for container names, but it does not automatically provide a hostname for the host machine; you would still need to use `--add-host` or similar to resolve the host by name.

24
Multi-Selecteasy

A Linux administrator writes a Python script to parse configuration files. Which TWO practices improve security and portability? (Select TWO.)

Select 2 answers
A.Validate all external input before processing
B.Use absolute paths for all file operations
C.Use sudo within the script to run privileged commands
D.Use raw_input() instead of input() in Python 2
E.Use shebang #!/usr/bin/env python3
AnswersA, E

Input validation prevents injection attacks and improves security.

Why this answer

Using #!/usr/bin/env python3 ensures the script uses the correct interpreter from the environment, enhancing portability. Validating all external input prevents injection attacks. The other options are either deprecated or bad practices.

25
MCQmedium

An administrator views the exhibit output. Which command should be used first to investigate why sshd failed?

A.systemctl status sshd.service
B.systemctl restart sshd.service
C.journalctl -u sshd.service
D.systemctl list-units
AnswerC

Shows the service logs for diagnosis.

Why this answer

The `journalctl -u sshd.service` command is the correct first step because it displays the systemd journal logs specifically for the sshd service, providing detailed error messages and timestamps that explain why the service failed. This diagnostic approach follows the principle of checking logs before attempting to restart or modify a service, as the logs contain the root cause information needed for troubleshooting.

Exam trap

The trap here is that candidates often jump to `systemctl status` or `systemctl restart` out of habit, not realizing that the journal logs provide the specific error details needed to diagnose a failure, and that restarting without investigation can hide the root cause.

How to eliminate wrong answers

Option A is wrong because `systemctl status sshd.service` shows the current state and recent log tail, but it may not show the full historical log output needed to diagnose a failure that occurred earlier. Option B is wrong because `systemctl restart sshd.service` attempts to restart the service without first understanding why it failed, which could mask the underlying issue or cause repeated failures. Option D is wrong because `systemctl list-units` lists all loaded units and their states, but it does not provide any diagnostic details about why a specific service like sshd failed.

26
MCQhard

A Linux server that hosts a critical database application has been experiencing occasional kernel panics. The administrator wants to ensure the system automatically reboots after a panic and logs the crash dump. Which sysctl parameter should be set?

A.kernel.panic_on_warn = 10
B.kernel.panic_on_oops = 10
C.kernel.panic_print = 10
D.kernel.panic = 10
AnswerD

Sets seconds before reboot after panic.

Why this answer

Option D is correct because setting `kernel.panic = 10` instructs the Linux kernel to wait 10 seconds after a kernel panic before automatically rebooting. This ensures the system recovers without manual intervention, and combined with a configured crash dump mechanism (e.g., kdump), the crash dump is captured before the reboot.

Exam trap

CompTIA often tests the distinction between parameters that cause a panic (`panic_on_oops`, `panic_on_warn`) and the parameter that controls the reboot delay after a panic (`kernel.panic`), leading candidates to confuse the cause with the recovery action.

How to eliminate wrong answers

Option A is wrong because `kernel.panic_on_warn` controls whether the kernel panics on a warning (WARN()), not the reboot behavior after a panic; setting it to 10 would be invalid as it expects 0 or 1. Option B is wrong because `kernel.panic_on_oops` determines if the kernel panics on an oops (a non-fatal error), not the timeout before reboot; it also expects a boolean value (0 or 1), not 10. Option C is wrong because `kernel.panic_print` controls the verbosity of kernel messages printed during a panic, not the reboot action or delay.

27
MCQhard

Given the Dockerfile in the exhibit, which best practice is being violated?

A.Not combining apt-get update and install in one RUN command
B.Using a non-LTS base image
C.Not using a .dockerignore file
D.Running apt-get update without cache cleanup
AnswerA

Should be combined: RUN apt-get update && apt-get install -y python3

Why this answer

The Dockerfile violates the best practice of combining `apt-get update` and `apt-get install` in a single RUN command. When these are separated, Docker caches the layer from `apt-get update`, so subsequent builds may use a stale package index, potentially installing outdated or vulnerable packages. Combining them ensures that the update and install happen atomically, reducing image size and guaranteeing a fresh package index.

Exam trap

CompTIA often tests the nuance that separating `apt-get update` and `apt-get install` is a caching and security violation, not just a style issue, and candidates may mistakenly focus on cache cleanup or .dockerignore as the primary problem.

How to eliminate wrong answers

Option B is wrong because using a non-LTS base image is not inherently a best practice violation; it may be acceptable for testing or specific requirements, and the question focuses on Dockerfile layering and caching, not base image choice. Option C is wrong because not using a .dockerignore file is a best practice for reducing build context size and preventing unintended files from being copied, but it is not the specific violation demonstrated by the given Dockerfile (which lacks combined apt commands). Option D is wrong because while running `apt-get update` without cache cleanup (e.g., `rm -rf /var/lib/apt/lists/*`) is a best practice to reduce image size, the primary violation in the exhibit is the separation of update and install into different RUN commands, not the absence of cleanup.

28
MCQmedium

A DevOps engineer is responsible for deploying a containerized web application on a Linux server running Docker. The application consists of three services: a frontend (Nginx), a backend (Node.js), and a database (PostgreSQL). The engineer uses Docker Compose to manage the stack. The deployment works correctly on a test environment, but when deployed to production, the frontend service fails to connect to the backend. Both services are on the same custom bridge network. The engineer checks the logs of the frontend container and sees 'getaddrinfo EAI_AGAIN backend-service'. The backend service is running and healthy. The engineer suspects a DNS resolution issue within the Docker network. Which of the following is the most likely cause and correct solution?

A.The frontend container is trying to resolve 'backend-service' but the backend container's hostname is different because the container_name is set in the docker-compose.yml.
B.The containers are not on the same network because the default network driver is 'host' instead of 'bridge'.
C.The backend service is listening on a different port than expected.
D.The Docker DNS resolver is caching an old IP address for the backend service.
AnswerA

If container_name is set, the service name is not used as the hostname; the frontend should use the container_name.

Why this answer

Option A is correct because the frontend container is attempting to resolve 'backend-service' via Docker's embedded DNS, but the backend container's hostname may differ if the `container_name` directive is set in the docker-compose.yml. Docker Compose creates a default hostname equal to the service name unless overridden by `container_name`. If `container_name` is set to something like 'my-backend', the DNS entry for 'backend-service' will not exist, causing an `EAI_AGAIN` (temporary failure in name resolution) error.

The solution is to either use the correct hostname (the service name) or set `container_name` to match the expected hostname.

Exam trap

The trap here is that candidates may assume the service name in docker-compose.yml always matches the DNS hostname, but Cisco tests the nuance that `container_name` overrides the default hostname, causing DNS resolution failures even when containers are on the same network.

How to eliminate wrong answers

Option B is wrong because the default network driver for Docker Compose is 'bridge', not 'host'; using 'host' would bypass Docker's DNS and cause different connectivity issues. Option C is wrong because the error message 'getaddrinfo EAI_AGAIN backend-service' indicates a DNS resolution failure, not a port mismatch; a port issue would produce a connection refused or timeout error. Option D is wrong because Docker's embedded DNS resolver does not cache IP addresses in a way that would cause an `EAI_AGAIN` error; it uses a short TTL and stale entries would result in a different error (e.g., connection timeout) or a successful resolution to an old IP.

29
MCQeasy

Refer to the exhibit. A system administrator notices that the cleanup script runs at 2:00 AM every day but sometimes does not execute. The log shows no output from the script. Which step should be taken to investigate?

A.Verify that the script is executable by the root user.
B.Check the syslog for cron execution messages.
C.Add a MAILTO directive to the crontab.
D.Change the script to log output to a file.
AnswerD

Redirecting stdout and stderr to a file allows administrators to see error messages and diagnose failures.

Why this answer

Option D is correct because the script runs but produces no log output, indicating it may be failing silently. Redirecting the script's stdout and stderr to a file (e.g., `>> /var/log/cleanup.log 2>&1`) captures error messages and output, allowing the administrator to see why the script sometimes does not execute or fails. This is the most direct way to diagnose a cron job that runs but yields no visible results.

Exam trap

The trap here is that candidates assume 'no output' means the script didn't run, leading them to check cron execution (Option B) or permissions (Option A), when the real issue is that the script runs but fails silently, requiring output redirection to diagnose the failure.

How to eliminate wrong answers

Option A is wrong because the script is already scheduled in root's crontab, implying it is owned and executed by root; if it were not executable, cron would typically log an error, not produce no output. Option B is wrong because checking syslog for cron execution messages would only confirm whether cron launched the job, but the problem states the script runs (the job is scheduled) yet produces no output—syslog won't reveal why the script itself fails. Option C is wrong because adding a MAILTO directive sends cron's stdout/stderr via email, but if the script produces no output (e.g., it exits silently before any echo), MAILTO will send an empty message, providing no diagnostic information about the failure.

30
MCQhard

A containerized application writes logs to /var/log/app.log. The administrator wants to ensure logs persist even if the container is removed. Which approach should be used?

A.Copy logs to a bind mount
B.Set the log driver to syslog
C.Redirect logs to stdout and use docker logs
D.Use a Docker volume mounted at /var/log
AnswerD

A Docker volume is managed by Docker and persists across container removal, retaining logs.

Why this answer

Option D is correct because Docker volumes are managed by Docker and persist independently of the container lifecycle. By mounting a volume at /var/log, the application writes logs directly to the volume, ensuring the data survives container removal and can be reused by other containers.

Exam trap

The trap here is that candidates may confuse bind mounts with Docker volumes, thinking that any host-path mapping provides automatic persistence, or they may assume that docker logs retains logs after container removal, when in fact it only works for running or stopped containers, not removed ones.

How to eliminate wrong answers

Option A is wrong because copying logs to a bind mount after they are written is not a native Docker approach; bind mounts rely on host directory paths and do not automatically persist logs if the container is removed without explicit copying. Option B is wrong because setting the log driver to syslog sends logs to the system's syslog service, but this does not guarantee persistence of the log file at /var/log/app.log within the container; it changes the output destination, not the file storage. Option C is wrong because redirecting logs to stdout and using docker logs only captures logs in the container's stdout stream, which is ephemeral and lost when the container is removed; docker logs does not provide persistent file storage.

31
Multi-Selecthard

Which THREE of the following are commonly used configuration management and automation tools in the Linux ecosystem? (Choose THREE.)

Select 3 answers
A.Terraform
B.Ansible
C.Salt
D.Puppet
E.Nagios
AnswersB, C, D

Agentless automation tool.

Why this answer

Ansible is a configuration management and automation tool that uses SSH for agentless communication and YAML-based playbooks to define desired system states. It is widely adopted in Linux environments for tasks such as software provisioning, configuration drift remediation, and orchestration, making it a correct choice for this question.

Exam trap

CompTIA often tests the distinction between infrastructure provisioning tools (like Terraform) and configuration management tools (like Ansible, Salt, Puppet), leading candidates to mistakenly include Terraform when the question explicitly asks for configuration management and automation tools in the Linux ecosystem.

32
MCQeasy

Which command is used to convert a file to uppercase?

A.tr '[a-z]' '[A-Z]'
B.All of the above
C.tr [:lower:] [:upper:]
D.tr a-z A-Z
AnswerB

All three options correctly convert lowercase to uppercase using tr.

Why this answer

Option B is correct because all three commands (A, C, D) are valid ways to convert lowercase letters to uppercase using the `tr` command. Each uses a different syntax—character ranges, POSIX character classes, or bracket expressions—but all achieve the same result. The question asks which command is used, and since all options work, 'All of the above' is the correct answer.

Exam trap

CompTIA often tests the candidate's ability to recognize that multiple valid syntaxes exist for the same `tr` operation, leading them to pick a single option when 'All of the above' is the comprehensive correct answer.

How to eliminate wrong answers

Option A is wrong because it is actually a valid command, not incorrect; however, it is not the only correct one. Option C is wrong because it is also a valid command using POSIX character classes, not incorrect. Option D is wrong because it is a valid shorthand using unquoted ranges, which works in most shells, but again it is not the only correct option.

The trap is that each individual option is technically correct, so the only fully correct answer is 'All of the above'.

33
MCQeasy

A DevOps engineer is writing a Bash script to check if the configuration file /etc/myapp.conf exists and is readable. The script must exit with code 0 if the file is readable, and exit with code 1 otherwise. The script will be used on systems with Bash as the default shell. Which code snippet correctly implements this logic using the most efficient syntax available in Bash?

A.`if [ -r /etc/myapp.conf ]; then exit 0; else exit 1; fi`
B.`if test -r /etc/myapp.conf; then exit 0; else exit 1; fi`
C.`if ( -r /etc/myapp.conf ) then exit 0; else exit 1; fi`
D.`if [[ -r /etc/myapp.conf ]]; then exit 0; else exit 1; fi`
AnswerD

[[ ]] is Bash-specific, more efficient for file tests.

Why this answer

Option D is correct because [[ ]] is a Bash keyword that provides more features and is more efficient for file tests in Bash. Options A and B are POSIX-compliant but less efficient. Option C has invalid syntax.

34
MCQhard

A company runs a critical web application on a single Linux server. The application consists of a Node.js backend and a PostgreSQL database. The server is running out of disk space frequently due to application logs. The administrator wants to implement a log rotation solution that is automated, minimizes data loss, and compresses old logs. The administrator has root access and wants to use built-in tools. Currently, logs are written to /var/log/app/access.log and /var/log/app/error.log. The application never closes its log files. Which of the following is the best course of action?

A.Configure the systemd journal to capture the application logs and set MaxRetentionSec.
B.Create a cron job that runs every hour to move the logs to a backup directory and restart the application.
C.Configure logrotate with daily rotation, compression, and the copytruncate option.
D.Configure logrotate with a weekly rotation and no copytruncate, since the application will eventually close the log files.
AnswerC

copytruncate allows rotation of open files without restarting.

Why this answer

Option C is correct because logrotate with the copytruncate option allows the log file to be rotated without requiring the application to close or reopen its file handles. This is essential since the application never closes its log files. Daily rotation with compression addresses the frequent disk space issue while minimizing data loss, and logrotate is a built-in Linux tool that runs automatically via cron.

Exam trap

The trap here is that candidates may assume logrotate always requires the application to close its log files (via postrotate scripts), but the copytruncate option is specifically designed for applications that keep file handles open, making it the correct choice when the application never closes its logs.

How to eliminate wrong answers

Option A is wrong because systemd-journald is designed for capturing systemd service logs, not for rotating existing log files written directly by an application; it does not handle files like /var/log/app/access.log, and MaxRetentionSec only controls journal retention, not file rotation. Option B is wrong because moving logs and restarting the application every hour would cause unnecessary application downtime and potential data loss, and it is not a built-in automated solution like logrotate. Option D is wrong because without copytruncate, logrotate would attempt to rename or move the log file, which would cause the application to continue writing to the old file (since it never closes its file handles), leading to lost logs and no rotation; weekly rotation is also too infrequent for a server running out of disk space frequently.

35
MCQmedium

A development team uses Git for version control and wants to automate the testing of every commit pushed to the repository. They have a Jenkins server running on a Linux machine. The team wants to automatically trigger a Jenkins pipeline job whenever a push is made to the main branch of their Git repository. The Jenkins server is behind a firewall and cannot be accessed from the internet. The Git repository is hosted on a private GitHub repository. Which of the following is the best approach to trigger the Jenkins job automatically?

A.Have developers manually click 'Build Now' in Jenkins after each push.
B.Configure Jenkins to poll the Git repository every minute for changes.
C.Configure a GitHub webhook to send a POST request to the Jenkins server.
D.Set up a cron job on the Git server to execute a script that triggers Jenkins.
AnswerB

Works behind firewall.

Why this answer

Option B is correct because Jenkins' polling mechanism allows it to periodically check the Git repository for changes, which works even when the Jenkins server is behind a firewall and cannot receive inbound webhooks. Polling every minute provides near-real-time automation without requiring internet access to the Jenkins server, making it the only viable option given the network constraint.

Exam trap

The trap here is that candidates assume webhooks are always the best automation trigger, but the firewall restriction makes polling the only practical solution when the Jenkins server cannot receive inbound connections.

How to eliminate wrong answers

Option A is wrong because manual triggering defeats the purpose of automation and does not scale for a development team pushing multiple commits. Option C is wrong because a GitHub webhook requires the Jenkins server to be reachable from the internet to receive the POST request, which is explicitly blocked by the firewall. Option D is wrong because the Git repository is hosted on GitHub (a cloud service), not on a local Git server; a cron job on the Git server is not possible when the server is not under the team's control.

36
Drag & Dropmedium

Drag and drop the steps to create and apply a systemd service unit in the correct order.

Drag steps to the numbered slots on the right, or tap a step then tap a slot.

Steps
Order

Why this order

Systemd service files require proper sections and then enabling/starting.

37
MCQeasy

A script named 'test.sh' contains '#!/bin/bash' and is located in the current directory. Which command runs the script in the current shell environment without forking a subshell?

A../test.sh
B.sh test.sh
C.bash test.sh
D.source test.sh
AnswerD

Executes in the current shell.

Why this answer

The `source` command (or its synonym `.`) executes the script in the current shell environment without forking a subshell. This is essential when you need the script to modify the current shell's environment, such as setting variables or changing directories, because a subshell would discard those changes upon exit.

Exam trap

CompTIA often tests the distinction between executing a script via its path (which forks a subshell) and sourcing it (which runs in the current shell), and candidates mistakenly think that `./test.sh` runs in the current shell because it is invoked directly from the command line.

How to eliminate wrong answers

Option A is wrong because `./test.sh` runs the script as an executable, which causes the kernel to fork a new subshell (based on the shebang) to execute the commands; the script does not run in the current shell. Option B is wrong because `sh test.sh` explicitly invokes the Bourne shell as a new process, forking a subshell that runs the script independently of the current shell. Option C is wrong because `bash test.sh` similarly launches a new Bash process as a subshell, isolating any environment changes from the parent shell.

38
MCQeasy

A system administrator wants to deploy a containerized application on a Linux server with minimal overhead and without a daemon. Which container runtime should be used?

A.containerd
B.LXC
C.Docker
D.Podman
AnswerD

Daemonless, rootless capable.

Why this answer

Podman is the correct choice because it is a daemonless container engine that runs containers directly under the user's process space, using a fork-exec model rather than a background daemon. This aligns with the requirement for minimal overhead and no daemon, as Podman does not require a persistent service to manage containers.

Exam trap

The trap here is that candidates often associate 'container runtime' with Docker or containerd, but the question specifically tests the distinction between daemon-based and daemonless architectures, where Podman's fork-exec model is the key differentiator.

How to eliminate wrong answers

Option A is wrong because containerd is a container runtime that operates as a daemon (typically managed by systemd) and is designed to be used as a building block for higher-level tools, not as a standalone daemonless runtime. Option B is wrong because LXC (Linux Containers) is a system-level virtualization tool that creates full system containers with an init daemon, not a lightweight application container runtime, and it relies on a daemon (lxcfs or lxc-monitord) for management. Option C is wrong because Docker uses a client-server architecture with a persistent daemon (dockerd) that runs in the background, which contradicts the requirement for no daemon and adds overhead.

39
MCQhard

A Linux system experiences high CPU usage from a process that appears to be a fork bomb. The administrator wants to prevent such attacks in the future by limiting the number of processes a user can create. Which configuration file should be modified, and what parameter should be set?

A.Set 'kernel.pid_max=100' in /etc/sysctl.conf
B.Set 'DefaultLimitNPROC=100' in /etc/systemd/system.conf
C.Add 'username hard nproc 100' in /etc/security/limits.conf
D.Add 'ulimit -u 100' to /etc/profile
AnswerC

Correctly limits the number of processes for a user via PAM.

Why this answer

Option C is correct because /etc/security/limits.conf is the PAM-based configuration file used to set per-user resource limits via the 'nproc' parameter. Adding 'username hard nproc 100' enforces a hard limit of 100 processes for that user, preventing a fork bomb from exhausting system resources.

Exam trap

CompTIA often tests the distinction between system-wide PID limits (kernel.pid_max) and per-user process limits (nproc), and candidates mistakenly choose A because they confuse maximum PID number with maximum number of processes.

How to eliminate wrong answers

Option A is wrong because 'kernel.pid_max' sets the maximum PID number, not a per-user process limit; it controls the total number of possible PIDs system-wide, not user-specific restrictions. Option B is wrong because 'DefaultLimitNPROC' in /etc/systemd/system.conf applies only to systemd-managed services, not to user login sessions or interactive shells, so it would not prevent a user-launched fork bomb. Option D is wrong because adding 'ulimit -u 100' to /etc/profile only affects interactive login shells and can be overridden by the user; it is not a persistent, system-wide enforcement mechanism.

40
Multi-Selectmedium

Which TWO commands are used to view logs in a systemd-based system? (Choose two.)

Select 2 answers
A.tail -f /var/log/messages
C.dmesg
D.journalctl
E.systemctl
AnswersC, D

dmesg shows kernel log messages.

Why this answer

C is correct because `dmesg` reads the kernel ring buffer, which contains boot-time and hardware-related log messages, and is commonly used to view logs on systemd-based systems. D is correct because `journalctl` is the primary command for querying and viewing logs from systemd's journal (managed by `systemd-journald`), which is the default logging subsystem in systemd-based distributions.

Exam trap

The trap here is that candidates often confuse `systemctl` (service management) with `journalctl` (log viewing) because both are systemd commands, and they may also mistakenly think `tail -f /var/log/messages` is universally available on modern systemd-based distributions.

41
MCQeasy

What does the `set -x` command do when placed at the top of a bash script?

A.Enables position parameters
B.Exits the script on error
C.Treats unset variables as errors
D.Displays each command before executing it
AnswerD

Correct. set -x enables debugging output, printing commands and their arguments as they are executed.

Why this answer

Option D is correct because `set -x` enables a shell debugging mode that prints each command (after expansion) to stderr before executing it. This is commonly used in bash scripts to trace execution flow and debug complex logic.

Exam trap

The trap here is that candidates confuse `set -x` with `set -e` (exit on error) or `set -u` (treat unset variables as error), because all three are common debugging options but serve distinct purposes.

How to eliminate wrong answers

Option A is wrong because position parameters (like $1, $2) are enabled by default in bash scripts; `set -x` does not affect them. Option B is wrong because exiting on error is controlled by `set -e`, not `set -x`. Option C is wrong because treating unset variables as errors is controlled by `set -u`, not `set -x`.

42
MCQeasy

You are a Linux system administrator for a small company. You have written a BASH script that checks disk usage and sends an email alert if any partition exceeds 90% usage. The script works when run manually but does not produce alerts when run via cron. Which of the following is the most likely cause?

A.The cron job's PATH variable does not include the directory where the mail command is located
B.The script has incorrect file permissions
C.The cron scheduler is disabled
D.The script uses relative paths to check partitions
AnswerA

The mail command is often in /usr/sbin, which may not be in cron's default PATH; the script fails to execute mail silently.

Why this answer

When a script runs manually, it inherits the user's interactive shell environment, including the PATH variable that typically includes directories like /usr/bin and /usr/local/bin where the mail command resides. However, cron jobs execute in a minimal environment with a very restricted PATH (often just /usr/bin:/bin). If the mail command is located in a directory not in cron's default PATH, such as /usr/sbin or /opt/bin, the script will fail silently when attempting to send the email, even though the disk usage check itself succeeds.

This is the most common cause of scripts working manually but failing under cron.

Exam trap

CompTIA often tests the concept that cron jobs have a restricted environment, particularly PATH, and candidates mistakenly focus on script permissions or relative paths instead of the missing command path in cron's minimal shell.

How to eliminate wrong answers

Option B is wrong because incorrect file permissions would prevent the script from executing at all, whether run manually or via cron, and the question states the script works when run manually. Option C is wrong because if the cron scheduler were disabled, no cron jobs would run at all, but the question implies the script is scheduled and runs (it just doesn't produce alerts). Option D is wrong because using relative paths to check partitions would cause the script to fail regardless of whether it runs manually or via cron, unless the working directory is explicitly set; the script works manually, so relative paths are not the issue.

43
MCQeasy

The script in the exhibit runs successfully but the administrator expects it to indicate success. What change should be made?

A.Replace $system_info with just system_info
B.Change 'exit 1' to 'exit 0'
C.Change the variable name to SYSTEM_INFO
D.Change 'exit 1' to 'exit 0' and remove the quotes around $system_info
AnswerB

Zero exit code indicates success.

Why this answer

The script uses 'exit 1' to terminate, which indicates a failure or error condition to the shell. The administrator expects the script to indicate success, so the exit code must be changed to 'exit 0', which is the standard Unix/Linux convention for successful execution. Exit codes are how scripts communicate their status to the calling process, and only exit 0 means success.

Exam trap

CompTIA often tests the fundamental distinction between exit codes 0 and 1, where candidates may mistakenly think that 'exit 1' is correct for a successful script or that variable naming or quoting affects the exit status.

How to eliminate wrong answers

Option A is wrong because removing the dollar sign from $system_info would treat it as a literal string instead of a variable reference, breaking the script's ability to use the stored value. Option C is wrong because changing the variable name to SYSTEM_INFO would not affect the exit code; variable names are case-sensitive but do not influence the script's success or failure status. Option D is wrong because while changing 'exit 1' to 'exit 0' is correct, removing the quotes around $system_info is unnecessary and could cause word splitting or globbing issues if the variable contains spaces or special characters, potentially breaking the script.

44
MCQeasy

An administrator needs to run a container using a specific user ID to match host file permissions. Which Docker option should be used when running the container?

A.-u 1001
B.-e USER=1001
C.-v /host:/container
D.--name mycontainer
AnswerA

Sets user ID inside container.

Why this answer

The `-u` (or `--user`) option in Docker allows you to run the container process with a specific user ID (UID) instead of the default root (UID 0). By specifying `-u 1001`, the container's main process will run as UID 1001, which can be matched to a host user's UID to ensure proper file ownership and permissions when accessing mounted volumes. This is essential for avoiding permission denied errors when the container writes files to a bind-mounted host directory.

Exam trap

The trap here is that candidates often confuse environment variables (like `-e USER=1001`) with the actual user ID change, mistakenly thinking setting an environment variable named `USER` will alter the process's effective UID, when in reality only `-u` or the `USER` directive in a Dockerfile changes the runtime user.

How to eliminate wrong answers

Option B is wrong because `-e USER=1001` sets an environment variable named `USER` inside the container, which does not change the effective user ID of the container process; the process still runs as root unless another mechanism (like `USER` in the Dockerfile) is used. Option C is wrong because `-v /host:/container` is a volume mount that maps a host directory into the container, but it does not control the user ID under which the container runs; file permissions are still determined by the container's UID. Option D is wrong because `--name mycontainer` simply assigns a custom name to the container for identification and management purposes, and has no effect on the user ID or file permissions.

45
Multi-Selecthard

Which THREE conditions must be met for a Linux container to run with user namespaces enabled? (Choose three.)

Select 3 answers
A.The container image must have a user with UID 0.
B.The container runtime must be configured to use user namespaces.
C.The kernel must support user namespaces (CONFIG_USER_NS=y).
D.The container must be started with root privileges.
E.The sysctl kernel.unprivileged_userns_clone must be set to 1.
AnswersB, C, E

Docker requires --userns-remap to enable user namespaces.

Why this answer

Option B is correct because user namespaces must be explicitly enabled in the container runtime configuration (e.g., `--userns=host` or `userns-remap` in Docker/Podman) to isolate the container's UID/GID mappings from the host. Without this configuration, the container will run in the default host namespace, negating the security benefits of user namespaces.

Exam trap

CompTIA often tests the misconception that a container must have UID 0 in its image or be started with root privileges to use user namespaces, when in fact user namespaces map an unprivileged host user to UID 0 inside the container.

46
Multi-Selecteasy

A Linux administrator is writing a systemd service unit file. Which three of the following directives are valid in the [Service] section? (Select THREE.)

Select 3 answers
A.Restart
B.After
C.Requires
D.User
E.ExecStart
AnswersA, D, E

Controls restart behavior of the service process.

Why this answer

A is correct because `Restart` is a valid directive in the `[Service]` section of a systemd service unit file. It controls whether and how the service is restarted when it exits, with common values like `always`, `on-failure`, or `no`. This directive is essential for ensuring service resilience in production environments.

Exam trap

CompTIA often tests the distinction between `[Unit]` and `[Service]` section directives, and the trap here is that candidates mistakenly apply dependency or ordering directives like `After` or `Requires` to the `[Service]` section, when they are only valid in `[Unit]`.

47
MCQeasy

The sysadmin receives the error shown in the exhibit. What is the most likely fix?

A.Add a readiness probe to the container.
B.Change the image tag to :latest.
C.Remove the requests section.
D.Add limits to the resources section.
AnswerD

The error explicitly requires limits to be specified.

Why this answer

The error indicates the container was killed due to an Out Of Memory (OOM) condition. Adding limits to the resources section constrains the container's memory usage, preventing it from exceeding the node's capacity and being terminated by the kernel OOM killer.

Exam trap

The trap here is that candidates confuse resource requests (which guarantee minimum resources) with limits (which cap usage), and mistakenly think removing requests or adding probes will fix an OOM error, when only a memory limit prevents the container from exhausting node memory.

How to eliminate wrong answers

Option A is wrong because a readiness probe checks if a container is ready to serve traffic, not memory limits; it does not prevent OOM kills. Option B is wrong because changing the image tag to :latest does not affect resource constraints and may introduce untested versions, but does not fix memory exhaustion. Option C is wrong because removing the requests section removes the minimum resource guarantee but does not cap memory usage; without limits, the container can still consume all available memory and be OOM-killed.

48
MCQeasy

An administrator wants to use Ansible to ensure that the `httpd` package is installed on all managed nodes. Which Ansible module should be used?

A.copy
B.command
C.yum
D.service
AnswerC

The yum module installs, removes, or upgrades packages using the yum package manager.

Why this answer

The `yum` module is the correct choice because it is a dedicated Ansible module for managing packages on Red Hat-based systems using the YUM package manager. It ensures the `httpd` package is installed by setting the `state: present` parameter, and it handles idempotency by checking the package status before making changes.

Exam trap

The trap here is that candidates may confuse the `service` module (which manages service state) with package installation, or mistakenly think the `command` module is acceptable for package management despite its lack of idempotency and error handling.

How to eliminate wrong answers

Option A is wrong because the `copy` module is used to copy files from the local machine to remote nodes, not to install packages. Option B is wrong because the `command` module runs arbitrary commands but lacks idempotency and package-specific features, making it error-prone for package management. Option D is wrong because the `service` module manages the state of services (e.g., started, stopped), not the installation of packages.

49
MCQhard

A container started with the above Compose configuration fails to set the system time (clock_settime syscall). Which additional capability is required?

A.SYS_NICE
B.SYS_TIME
C.SYS_RESOURCE
D.SYS_CLOCK
AnswerB

Required for changing the system clock.

Why this answer

The `clock_settime` syscall requires the `SYS_TIME` capability to modify the system clock. In Docker Compose, capabilities are added via the `cap_add` directive, and without `SYS_TIME`, the container lacks the privilege to change the system time, resulting in a failure.

Exam trap

CompTIA often tests the distinction between `SYS_TIME` and the non-existent `SYS_CLOCK` to trap candidates who assume a capability name must match the syscall name exactly.

How to eliminate wrong answers

Option A is wrong because `SYS_NICE` allows changing process priority and scheduling, not system time. Option C is wrong because `SYS_RESOURCE` controls resource limits (e.g., ulimit overrides), not clock operations. Option D is wrong because `SYS_CLOCK` is not a valid Linux capability; the correct capability for clock operations is `SYS_TIME`.

50
MCQeasy

A Linux administrator needs to automate daily database backups and ensure the job runs even if the system is rebooted. Which approach should be used?

A.Schedule the backup using the at command.
B.Add a cron job in /etc/crontab.
C.Create a systemd timer unit that triggers a service.
D.Use anacron to run the job daily.
AnswerC

Timers can catch up after reboot.

Why this answer

A systemd timer unit is the correct approach because it can be configured to trigger a service unit (e.g., a backup script) on a daily schedule, and systemd ensures that timers persist across reboots and will catch up on missed runs if the system was down. This provides reliable, dependency-aware scheduling integrated with the init system, unlike cron which may miss jobs during downtime.

Exam trap

The trap here is that candidates often default to cron (option B) for recurring tasks, but the requirement 'even if the system is rebooted' specifically tests knowledge of systemd timers' persistent and catch-up capabilities, which cron lacks.

How to eliminate wrong answers

Option A is wrong because the `at` command schedules a one-time job, not a recurring daily task, and does not automatically re-run after a reboot. Option B is wrong because a cron job in /etc/crontab runs only when the system is powered on at the scheduled time; if the system is rebooted or down during that time, the job is missed entirely without catch-up logic. Option D is wrong because anacron is designed for systems that are not running 24/7, but it does not integrate with systemd's service management and is not the recommended modern approach for ensuring a job runs after a reboot on a systemd-based Linux distribution.

51
Multi-Selecteasy

A container produces a large amount of log output to stdout. Which TWO methods effectively manage log size in a production environment?

Select 2 answers
A.Use docker logs --tail 100 to limit output
B.Configure journald limits for container logging
C.Use a bind mount to redirect logs to /dev/null
D.Configure the application inside the container to log to a file
E.Set the --log-opt max-size=10m when running the container
AnswersB, E

Journald can be configured to cap log storage for containers.

Why this answer

Option B is correct because journald can be configured to limit the size of log data it stores, including container logs that are sent to the journal. In a production environment, setting `SystemMaxUse=` or `MaxRetentionSec=` in `/etc/systemd/journald.conf` prevents unbounded log growth. Option E is correct because Docker's `--log-opt max-size=10m` truncates the container's log file when it reaches 10 MB, rotating it automatically, which directly manages log size at the container runtime level.

Exam trap

The trap here is that candidates confuse `docker logs --tail` (a display filter) with actual log size management, or assume that redirecting logs to `/dev/null` is a valid production strategy, when in fact it destroys forensic data and violates operational best practices.

52
MCQhard

A Linux administrator is writing a Bash script to automate the backup of a database. The script must run a pre-backup command, check its exit status, and if successful, proceed with the backup; otherwise, log an error and exit. Which code snippet correctly implements this logic?

A.set -e pre_backup_cmd backup_cmd
B.pre_backup_cmd && backup_cmd || echo 'Error' >&2
C.pre_backup_cmd if [ $? -ne 0 ]; then echo 'Error' >&2; exit 1; fi backup_cmd
D.(pre_backup_cmd; if [ $? -ne 0 ]; then echo 'Error' >&2; exit 1; fi) && backup_cmd
AnswerC

This correctly captures the exit status of the pre_backup_cmd and handles failure before proceeding.

Why this answer

Option C correctly runs the pre-backup command, then checks its exit status with `$?`. If the exit status is not zero (indicating failure), it logs an error to stderr and exits with code 1. Only if the pre-backup command succeeds does the script proceed to the backup command.

This matches the requirement exactly: check exit status, log error on failure, and exit.

Exam trap

The trap here is that candidates often choose option B because they think `&&` and `||` provide equivalent conditional logic, but they overlook that the `||` will also catch failures from the backup command itself, not just the pre-backup command, violating the requirement.

How to eliminate wrong answers

Option A is wrong because `set -e` causes the script to exit immediately on any command failure, but it does not log an error message before exiting, nor does it allow conditional logic to proceed with backup only on success. Option B is wrong because the `||` after `backup_cmd` will also trigger the error logging if `backup_cmd` itself fails, even if `pre_backup_cmd` succeeded — this does not match the requirement to only log an error when the pre-backup command fails. Option D is wrong because the subshell `( ... )` runs the pre-backup command and error handling inside a child shell; if the pre-backup command fails, the `exit 1` inside the subshell only exits the subshell, not the main script, and the `&& backup_cmd` will not run, but the main script continues without exiting — failing to meet the requirement to exit the script on pre-backup failure.

53
MCQeasy

A junior administrator is asked to automate the backup of a configuration file every night at 11 PM. The script /usr/local/bin/backup.sh already exists. Which command should the administrator run to schedule this task?

A.systemctl start backup.timer
B.at 23:00 /usr/local/bin/backup.sh
C.echo "0 23 * * * /usr/local/bin/backup.sh" | crontab -
D.nohup /usr/local/bin/backup.sh &
AnswerC

Correct. This appends a cron job entry to the crontab, scheduling the script to run daily at 23:00.

Why this answer

Option C is correct because the `crontab -` command reads from standard input and installs the cron job. The line `0 23 * * * /usr/local/bin/backup.sh` specifies that the script should run at 23:00 (11 PM) every day, matching the requirement exactly. This is the standard method for scheduling recurring tasks in Linux using cron.

Exam trap

The trap here is that candidates often confuse `at` (for one-time tasks) with `cron` (for recurring tasks), or assume `systemctl start` can create a timer on the fly without a pre-existing timer unit file.

How to eliminate wrong answers

Option A is wrong because `systemctl start backup.timer` would start a systemd timer unit, but no such timer has been defined or enabled; this command does not create a new schedule and would fail if the timer unit does not exist. Option B is wrong because the `at` command is used for one-time scheduled tasks, not recurring nightly backups; `at 23:00` would schedule the script to run only once at the next 11 PM, not every night. Option D is wrong because `nohup` runs the script in the background with immunity to hangups, but it does not schedule the task for a future time; it executes immediately and exits.

54
MCQhard

A Linux administrator is writing a script that must wait for a background process to finish before continuing. The process ID is stored in a variable. Which command should be used to wait for this process?

A.sleep 10
B.wait
C.wait $PID
D.kill -0 $PID
AnswerC

Waits for specific process.

Why this answer

Option C is correct because the `wait` command in Bash, when given a specific process ID (PID), suspends execution of the calling shell script until that background process terminates. This directly fulfills the requirement to wait for a specific background process whose PID is stored in a variable.

Exam trap

CompTIA often tests the distinction between `wait` (which waits for process completion) and `kill -0` (which only checks process existence), leading candidates to mistakenly choose `kill -0` as a waiting mechanism.

How to eliminate wrong answers

Option A is wrong because `sleep 10` simply pauses execution for a fixed 10 seconds, regardless of whether the background process has finished, and does not use the stored PID. Option B is wrong because `wait` without arguments waits for all background processes to finish, not a specific process identified by the PID variable. Option D is wrong because `kill -0 $PID` only checks whether a process with that PID exists and is accessible, sending no signal; it does not wait for the process to complete.

55
MCQhard

Refer to the exhibit. The service fails to start with the error 'Failed to start My Service: Unit not found'. What is the most likely cause?

A.The User specified does not exist.
B.The service file is not in the correct directory.
C.The network target is not reached.
D.The ExecStart script is missing.
AnswerB

Unit files must be placed in /etc/systemd/system/ or /lib/systemd/system/ to be recognized.

Why this answer

The error 'Unit not found' indicates that systemd cannot locate the service unit file. Systemd service files must be placed in specific directories such as /etc/systemd/system/ or /usr/lib/systemd/system/. If the file is in the wrong directory, systemd will not recognize the unit, causing the 'Unit not found' error.

Option B correctly identifies this as the most likely cause.

Exam trap

CompTIA often tests the distinction between 'unit not found' (file location issue) and 'command not found' or 'exec format error' (missing executable or script), leading candidates to incorrectly choose the missing ExecStart script option.

How to eliminate wrong answers

Option A is wrong because a non-existent User would cause a different error, such as 'Failed to determine user credentials' or 'User 'xxx' not found', not 'Unit not found'. Option C is wrong because the network target not being reached would result in a dependency failure or timeout, not a 'Unit not found' error. Option D is wrong because a missing ExecStart script would produce an error like 'Exec format error' or 'No such file or directory' when the service attempts to start, not a failure to find the unit itself.

56
Multi-Selectmedium

Which TWO statements are true regarding the use of Ansible for automation? (Choose TWO.)

Select 2 answers
A.Ansible requires a dedicated master server to manage nodes.
B.Ansible playbooks are written in YAML.
C.Ansible is agentless and uses SSH for communication.
D.Ansible uses a pull-based model where nodes fetch configurations from a central server.
E.Ansible modules are written in Ruby.
AnswersB, C

Ansible playbooks are YAML files that define automation tasks.

Why this answer

Option B is correct because Ansible playbooks are written in YAML (YAML Ain't Markup Language), which is a human-readable data serialization standard. YAML allows for simple, declarative syntax to define automation tasks, variables, and handlers, making playbooks easy to write and maintain without requiring programming expertise.

Exam trap

The trap here is that candidates often confuse Ansible's push-based model with pull-based tools like Puppet or Chef, or assume a master server is required because other automation tools use a master-agent architecture.

57
MCQmedium

You are managing a containerized microservices environment using Podman. One of the services needs to access a PostgreSQL database running in a separate container. The database container is named 'db' and uses the default bridge network. The application container is launched with the command: podman run -d --name app --network host myapp. The application fails to connect to the database using the hostname 'db'. Which change should you resolve the issue?

A.Use a user-defined network and connect both containers
B.Use --link db:db when running app container
C.Set environment variable DB_HOST=localhost
D.Run app container on the same network as db using --network bridge
AnswerA

A user-defined network provides automatic DNS resolution, allowing 'db' to resolve to the database container.

Why this answer

The default bridge network in Podman does not provide automatic DNS resolution between containers by name. When the app container uses `--network host`, it shares the host's network stack and is not connected to any container network, so it cannot resolve the container name 'db'. A user-defined network enables built-in DNS resolution, allowing containers to communicate by name.

Connecting both containers to the same user-defined network resolves the connectivity issue.

Exam trap

CompTIA often tests the misconception that the default bridge network supports automatic DNS resolution by container name, when in reality only user-defined networks provide that feature in both Podman and Docker.

How to eliminate wrong answers

Option B is wrong because `--link` is a legacy Docker feature not supported in Podman; Podman uses DNS-based service discovery on user-defined networks instead. Option C is wrong because setting `DB_HOST=localhost` would point to the host's loopback interface, but the database container is not listening on the host's loopback unless port mapping is explicitly configured, which is not the case here. Option D is wrong because `--network bridge` is the default network mode, but the app container is already using `--network host`, which overrides any other network setting; even if both containers were on the default bridge, they would not be able to resolve each other by name without a user-defined network.

58
Multi-Selecthard

A Linux administrator needs to implement a cron job that runs a script every day at 2:30 PM. Which TWO cron schedule expressions are equivalent?

Select 2 answers
A.30 14 * * *
B.30 2 * * * PM
C.30 2 * * *
D.30 2 * * *
E.30 14 * * *
AnswersA, E

2:30 PM.

Why this answer

In cron syntax, the first field is minute (0-59), the second is hour (0-23) in 24-hour format. 2:30 PM corresponds to hour 14 in 24-hour time. Therefore, '30 14 * * *' correctly specifies the job runs at minute 30 of hour 14 every day. Option A and E are identical and both use the correct 24-hour representation.

Exam trap

CompTIA often tests the 24-hour vs 12-hour clock confusion in cron expressions, where candidates mistakenly use '2' for 2 PM instead of converting to '14'.

59
Matchingmedium

Match each Linux process signal to its typical action.

Drag a concept onto its matching description — or click a concept then click the description.

Concepts
Matches

Hangup, often reload config

Interrupt from keyboard (Ctrl+C)

Force kill (cannot be caught)

Terminate gracefully

Stop/pause process (cannot be caught)

Why these pairings

Signals are used for inter-process communication.

60
MCQmedium

A sysadmin wants to run a containerized web application using Podman. The container needs to persist data across restarts. Which approach ensures data persistence?

A.Run the container with --restart always.
B.Mount a host directory as a volume using -v.
C.Include the data using COPY in the Dockerfile.
D.Use docker commit to save changes.
AnswerB

Mounting a volume allows data to be stored on the host, surviving container restarts and removal.

Why this answer

Option B is correct because mounting a host directory as a volume using the `-v` flag (e.g., `podman run -v /host/path:/container/path ...`) ensures that data written inside the container is stored on the host filesystem. This data persists independently of the container's lifecycle, surviving container restarts, stops, or even removal. Podman, like Docker, treats volumes as external storage that outlives the container.

Exam trap

The trap here is that candidates confuse container restart policies (like `--restart always`) with data persistence, assuming that keeping the container running automatically preserves its data, when in fact the container's writable layer is ephemeral and lost on removal.

How to eliminate wrong answers

Option A is wrong because `--restart always` only controls the container's restart policy (e.g., after a crash or reboot), but it does not preserve data when the container is removed or its filesystem is replaced; any data written inside the container's writable layer is lost upon container deletion. Option C is wrong because the `COPY` instruction in a Dockerfile bakes data into the container image at build time, making it read-only and immutable; it cannot persist runtime data across restarts or container updates. Option D is wrong because `docker commit` creates a new image from a container's current state, which is a manual, snapshot-based approach that does not provide ongoing persistence; it also requires explicit action and bloats image layers, and is not a standard method for persistent storage in production.

61
MCQmedium

An administrator wants to run a script every Monday at 3:00 PM using a systemd timer. Which unit file configuration is correct for the timer?

A.OnCalendar=Mon *-*-* 15:00:00
B.OnCalendar=weekly Monday 15:00
C.ExecStart=/usr/local/bin/script.sh
D.OnCalendar=daily 15:00
AnswerA

Correct syntax for Monday at 3 PM.

Why this answer

Option A is correct because systemd timer units use the `OnCalendar=` directive with a calendar event format that follows `DayOfWeek Year-Month-Day Hour:Minute:Second`. The pattern `Mon *-*-* 15:00:00` specifies every Monday at 15:00:00, where the asterisks act as wildcards for any year, month, and day. This matches the requirement to run a script every Monday at 3:00 PM.

Exam trap

CompTIA often tests the distinction between timer unit directives and service unit directives, and the trap here is that candidates mistakenly think `ExecStart=` belongs in the timer file or confuse the `OnCalendar=` syntax with cron-style or human-readable formats like 'weekly Monday 15:00'.

How to eliminate wrong answers

Option B is wrong because `OnCalendar=weekly Monday 15:00` is not a valid systemd calendar event format; systemd does not accept the keyword 'weekly' combined with a day name and time in that syntax, and the correct format requires a full timestamp with wildcards. Option C is wrong because `ExecStart=` is a directive for service units, not timer units; timer units use `OnCalendar=` or other time-based triggers, and `ExecStart=` would be placed in the corresponding service unit file. Option D is wrong because `OnCalendar=daily 15:00` would run the script every day at 15:00, not specifically on Mondays, failing the requirement for a weekly Monday-only schedule.

62
MCQmedium

An administrator runs the commands shown in the exhibit. The container is accessible via curl using the container IP. However, the administrator cannot access the web server using the host's IP address on port 80. What is the most likely cause?

A.The container's IP address is incorrect.
B.The container's port 80 is not published to the host.
C.Nginx is configured to listen on a different port.
D.The container is not running.
AnswerB

No -p option was used; port is only accessible on the container's network.

Why this answer

Option B is correct because the administrator ran `docker run -d nginx` without the `-p` or `--publish` flag, which means port 80 inside the container is not mapped to any port on the host. The container is accessible via its own IP because Docker networking allows direct container-to-container communication, but the host's IP on port 80 remains unbound, so curl to the host IP fails. Publishing the port with `-p 80:80` would expose the container's port 80 on the host's interface.

Exam trap

The trap here is that candidates assume a running container with a working service is automatically accessible on the host's IP, but Docker requires explicit port publishing to bridge the host network namespace to the container's network namespace.

How to eliminate wrong answers

Option A is wrong because the container's IP address is correct—the administrator can curl the container IP successfully, proving the container is reachable at that address. Option C is wrong because Nginx inside the official nginx container listens on port 80 by default, and the successful curl to the container IP confirms the web server is responding on that port. Option D is wrong because the container is running (the `docker ps` output would show it, and curl to the container IP works), so the issue is not a stopped container.

63
Multi-Selectmedium

A Linux engineer needs to ensure a bash script runs with strict error handling. Which TWO of the following should be included? (Choose two.)

Select 2 answers
A.set -o pipefail
B.set -n
C.set -e
D.set -x
E.shopt -s histappend
AnswersA, C

Exit on pipeline failure.

Why this answer

Option A, 'set -o pipefail', is correct because it ensures that if any command in a pipeline fails (returns a non-zero exit status), the entire pipeline's exit status reflects that failure. Without it, only the last command's exit status is considered, which can mask errors in earlier pipeline stages. Option C, 'set -e', is correct because it causes the script to exit immediately upon any command returning a non-zero exit status, preventing silent failures from propagating.

Exam trap

CompTIA often tests the distinction between debugging options (set -x) and error-handling options (set -e, set -o pipefail), leading candidates to mistakenly choose set -x as a strict error-handling mechanism.

64
MCQeasy

A junior administrator needs to view the logs of a running container named 'webapp'. Which command should be used?

A.docker attach webapp
B.docker logs webapp
C.docker inspect webapp
D.docker stats webapp
AnswerB

Shows logs.

Why this answer

The `docker logs webapp` command retrieves the stdout and stderr output streams from the container's main process, which is the standard way to view logs for a running or stopped container. This is the correct approach because Docker captures these streams and stores them in a JSON file on the host, accessible via the `docker logs` command.

Exam trap

CompTIA often tests the distinction between `docker attach` (interactive session) and `docker logs` (passive log retrieval), trapping candidates who confuse attaching to a container's console with viewing its log history.

How to eliminate wrong answers

Option A is wrong because `docker attach` connects the terminal to the container's main process's stdin/stdout/stderr, which is used for interactive debugging and can block the terminal, not for viewing historical logs. Option C is wrong because `docker inspect` returns detailed metadata about the container (e.g., configuration, network settings, mounts) in JSON format, not the log output. Option D is wrong because `docker stats` displays live resource usage metrics (CPU, memory, network I/O) for running containers, not log content.

65
MCQhard

A sysadmin runs the command and sees the exhibit output. What is the most likely cause of the db pod's status?

A.The container is out of memory.
B.The node running the pod is unreachable.
C.The pod does not have enough CPU resources.
D.The application inside the container is repeatedly crashing.
AnswerD

CrashLoopBackOff means the container exits with an error and is being restarted repeatedly.

Why this answer

The pod's status shows a high restart count (e.g., 5+ restarts) in the output of `kubectl get pods`, which is the classic indicator of a CrashLoopBackOff state. This occurs when the container's entrypoint process exits repeatedly, causing the container to crash and be restarted by the kubelet, until the back-off delay increases. The most likely cause is that the application inside the container is repeatedly crashing, not a resource or node issue.

Exam trap

The trap here is that candidates often confuse a high restart count with a resource exhaustion issue (OOM or CPU), but the key differentiator is the specific exit code and status message shown in `kubectl describe pod` or `kubectl logs`.

How to eliminate wrong answers

Option A is wrong because an out-of-memory (OOM) condition would typically show an OOMKilled status or an Exit Code 137, not a high restart count with CrashLoopBackOff. Option B is wrong because if the node were unreachable, the pod would show a NodeLost or Unknown status, not a running pod with restarts. Option C is wrong because insufficient CPU resources would result in a ContainerCreating or Pending state due to unschedulable pod, not a running pod that repeatedly crashes.

66
MCQeasy

Which command will create a compressed tar archive of a directory?

A.tar -czf archive.tar.gz dir
B.tar -xzf archive.tar.gz
C.tar -cf archive.tar dir
D.tar -tf archive.tar
AnswerA

This creates a gzip compressed tar archive.

Why this answer

Option A is correct because the `-czf` flags combine `-c` (create archive), `-z` (compress with gzip), and `-f` (specify archive file name). This creates a compressed tar archive of the specified directory, outputting a `.tar.gz` file. The command `tar -czf archive.tar.gz dir` is the standard syntax for this operation.

Exam trap

CompTIA often tests the distinction between create (`-c`), extract (`-x`), and list (`-t`) flags, and the requirement of `-z` for gzip compression, causing candidates to confuse `-czf` with `-xzf` or omit `-z` entirely.

How to eliminate wrong answers

Option B is wrong because `-xzf` extracts (decompresses) an existing archive, not creates one; the `-x` flag stands for extract. Option C is wrong because `-cf` creates an uncompressed tar archive (`.tar` only), missing the `-z` flag for gzip compression. Option D is wrong because `-tf` lists the contents of an existing archive without creating or compressing anything.

67
MCQhard

A DevOps team uses Git for version control of Ansible playbooks. They notice that a recent commit introduced errors in the playbook. Which Git command sequence should they use to temporarily revert to a previous commit while preserving the faulty commit in history?

A.git checkout HEAD~1
B.git revert HEAD
C.git reset --hard HEAD~1
D.git branch -d faulty-branch
AnswerB

Creates inverse commit, keeps history.

Why this answer

The `git revert HEAD` command creates a new commit that undoes the changes introduced by the most recent commit, effectively reverting the playbook to its previous state while preserving the faulty commit in the project history. This is the correct approach for a team using shared repositories because it maintains a linear, non-destructive history that can be safely pushed to a remote without force-pushing.

Exam trap

The trap here is that candidates confuse `git revert` (which creates a new commit to undo changes) with `git reset` (which removes commits from history), leading them to choose the destructive `git reset --hard` option when the question explicitly requires preserving the faulty commit in history.

How to eliminate wrong answers

Option A is wrong because `git checkout HEAD~1` detaches the HEAD to the previous commit, putting the repository in a detached HEAD state; it does not create a new commit and does not preserve the faulty commit in the active branch history. Option C is wrong because `git reset --hard HEAD~1` permanently removes the faulty commit from the branch history, discarding its changes and rewriting history, which is destructive and dangerous for shared branches. Option D is wrong because `git branch -d faulty-branch` deletes a branch named 'faulty-branch', which does not address reverting the most recent commit on the current branch and is irrelevant to the scenario.

68
Multi-Selecthard

A system administrator is troubleshooting a bash script that fails when run from cron but works when run from the terminal. Which two factors could explain this behavior? (Select TWO.)

Select 2 answers
A.The script uses interactive commands
B.The script uses a different shell interpreter
C.The script uses absolute paths
D.The script runs with a different user ID
E.Different PATH environment variable
AnswersA, E

Commands like read, vi, or those requiring a terminal fail non-interactively.

Why this answer

Option A is correct because interactive commands (e.g., `read`, `select`, or commands that require a TTY) fail when run from cron, as cron does not allocate a terminal. The script expects user input or terminal interaction, which is not available in the cron environment, causing it to hang or error out. Option E is correct because cron runs with a minimal PATH (often `/usr/bin:/bin`), so the script may fail to locate commands that are found in the user's interactive shell PATH (e.g., `/usr/local/bin`).

Exam trap

CompTIA often tests the misconception that cron runs scripts with the same environment as the user's interactive shell, leading candidates to overlook PATH and interactive command issues in favor of user ID or interpreter differences.

69
Multi-Selecteasy

An administrator wants to ensure a critical monitoring script runs every day at 2 AM and sends output to a log file. Which THREE items are essential in the crontab entry? (Select THREE.)

Select 3 answers
A.SHELL=/bin/bash
B.RUNLEVEL=3
C.0 2 * * * /usr/local/bin/script.sh
D.MAILTO=admin@example.com
E.PATH=/usr/local/bin:/usr/bin
AnswersA, C, E

If the script uses bash-specific features, setting SHELL is required; otherwise, cron uses /bin/sh.

Why this answer

Option A is correct because the SHELL variable in a crontab entry defines which shell interpreter is used to execute the cron job. By default, cron uses /bin/sh, but setting SHELL=/bin/bash ensures that bash-specific syntax, aliases, and features (such as [[ ]] or source) are available for the monitoring script. Without this, the script might fail if it relies on bash extensions.

Exam trap

CompTIA often tests the misconception that MAILTO is required for logging output, when in fact output redirection (e.g., >> /var/log/script.log 2>&1) is what sends output to a file, and MAILTO is only for email delivery.

70
Multi-Selectmedium

A Linux administrator uses Podman for container management. Which TWO commands display a list of currently running containers?

Select 2 answers
A.docker ps
B.podman inspect
C.podman images
D.podman container ls
E.podman ps
AnswersD, E

Correct: `podman container ls` is an alias for `podman ps`.

Why this answer

Option D is correct because `podman container ls` is the explicit Podman command to list running containers, equivalent to `podman ps`. Option E is also correct because `podman ps` is the standard shorthand for listing running containers in Podman, mirroring Docker's `docker ps` syntax. Both commands display the same output of currently active containers.

Exam trap

The trap here is that candidates may assume `docker ps` works identically in Podman due to CLI compatibility, but the exam expects Podman-native commands, and they may overlook that `podman container ls` is the explicit form while `podman ps` is the shorthand.

71
MCQhard

A systemd timer unit is configured to run a service every hour but the service never executes. The timer shows as active and enabled. Which of the following is the most likely cause?

A.The service unit is masked
B.The timer is not started
C.The service unit is not enabled
D.The timer unit has a mistake in the OnCalendar directive
AnswerA

A masked service cannot be started by any method, including timers.

Why this answer

When a systemd timer unit is active and enabled but the associated service never executes, the most likely cause is that the service unit is masked. A masked unit is symlinked to /dev/null, which prevents systemd from starting it regardless of timer triggers. The timer itself runs correctly, but systemd silently ignores the request to activate the masked service.

Exam trap

The trap here is that candidates confuse 'masked' with 'disabled' or assume a timer will still start a disabled service, but systemd will not start a masked service under any circumstances.

How to eliminate wrong answers

Option B is wrong because the timer is explicitly stated as active and enabled, meaning it has been started. Option C is wrong because the service unit does not need to be enabled for a timer to start it; the timer activation is independent of the service's enablement status. Option D is wrong because if the OnCalendar directive had a mistake, the timer would likely show as inactive or fail to trigger, but the question states the timer is active and enabled, implying the directive is syntactically correct.

72
MCQmedium

A script receives a JSON object where keys are user IDs. Which command extracts the 'status' of user id '123'?

A.echo "$json" | jq '.status'
B.echo "$json" | jq '. | select(.id=="123") | .status'
C.echo "$json" | jq '.[] | select(.id=="123") | .status'
D.echo "$json" | jq '.["123"].status'
AnswerD

Correctly accesses the object by key and extracts status.

Why this answer

Option D is correct because the JSON object uses user IDs as keys, so `.["123"]` directly accesses the object property for user ID '123', and `.status` extracts the 'status' field from that nested object. The `jq` syntax `.["key"]` is the standard way to access a property by a string key in a JSON object.

Exam trap

The trap here is that candidates often default to using `select(.id=="123")` as if the JSON were an array of objects with an 'id' field, failing to recognize that the user IDs are the object keys themselves, requiring direct key access with `.["123"]`.

How to eliminate wrong answers

Option A is wrong because `.status` attempts to access a top-level 'status' key, but the JSON object's top-level keys are user IDs, not 'status'. Option B is wrong because `. | select(.id=="123")` assumes the JSON is an array of objects with an 'id' field, but the input is an object keyed by user IDs, not an array. Option C is wrong because `.[]` iterates over the values of the object, but then `select(.id=="123")` again incorrectly expects an 'id' field within each value, whereas the user ID is the key, not a field inside the value.

73
MCQhard

A system administrator is troubleshooting a Docker container that exits immediately after starting. The container is built from a minimal image that runs a short-lived command. Which change will keep the container running?

A.Modify the Dockerfile to use CMD ["sh"] instead of CMD ["echo", "hello"]
B.Use -d flag to run in detached mode
C.Restart the container with --restart=always
D.Allocate a pseudo-TTY with -t flag
AnswerA

Running a shell as the main process will keep the container running indefinitely.

Why this answer

Option A is correct because the container exits immediately when its main process finishes. By changing the CMD from `["echo", "hello"]` (which prints a message and exits) to `["sh"]`, the container runs an interactive shell that waits for input, keeping the process alive and the container running. In Docker, a container lives only as long as its PID 1 process runs.

Exam trap

CompTIA often tests the misconception that detached mode (`-d`) or restart policies (`--restart=always`) can keep a container running indefinitely, but the core requirement is that the container's main process must not terminate.

How to eliminate wrong answers

Option B is wrong because the `-d` flag runs the container in detached mode, but it does not change the fact that the command inside the container is short-lived; the container will still exit immediately after the command finishes. Option C is wrong because `--restart=always` only restarts the container after it exits, but it does not prevent the immediate exit; the container will keep restarting in a loop rather than staying running continuously. Option D is wrong because allocating a pseudo-TTY with `-t` does not keep the container alive; it only provides a terminal interface, but if the command finishes, the container still exits.

74
MCQhard

A security team requires that all scripts run from a specific directory must be signed with a GPG key before execution. Which Linux feature can enforce this policy?

A.IMA/EVM with fs-verity
B.setuid bit
C.dm-verity
D.SELinux boolean
AnswerA

IMA/EVM can enforce that files are signed and verified before execution.

Why this answer

IMA/EVM (Integrity Measurement Architecture / Extended Verification Module) with fs-verity is the correct choice because it provides file-level integrity enforcement by requiring a valid GPG signature on scripts before execution. fs-verity enables per-file Merkle tree verification, and IMA can be configured to measure and enforce signatures, ensuring only signed scripts from the specified directory are allowed to run.

Exam trap

The trap here is that candidates confuse dm-verity (block-level integrity for read-only filesystems) with fs-verity (file-level integrity for mutable files), leading them to choose dm-verity despite it not supporting per-file signing enforcement.

How to eliminate wrong answers

Option B is wrong because the setuid bit allows a script to run with the permissions of its owner, not enforce GPG signing; it has no integrity verification capability. Option C is wrong because dm-verity provides block-level integrity verification for read-only block devices (e.g., system partitions), not per-file signing enforcement for scripts in a directory. Option D is wrong because SELinux booleans toggle policy features (e.g., allowing or denying certain operations) but cannot enforce GPG signature requirements on scripts; they lack cryptographic verification.

75
MCQeasy

A system administrator wants to create a new user and set a password in a single command as part of a provisioning script. Which command accomplishes this?

A.passwd user1 password
B.echo 'user1:password' | chpasswd
C.useradd -m -p password user1
D.usermod -p password user1
AnswerB

correctly reads from stdin.

Why this answer

Option B is correct because the `chpasswd` command reads username:password pairs from standard input, allowing a single command to create or update a user's password. When combined with `echo`, it sets the password for a new or existing user in one line, which is ideal for provisioning scripts. The `-p` option in `useradd` expects an already-hashed password, not a plaintext one, and `passwd` does not accept the password as an argument for security reasons.

Exam trap

The trap here is that candidates often assume `passwd` or `useradd -p` can accept a plaintext password directly, but the exam tests the understanding that these commands require either interactive input or a pre-hashed password, making `chpasswd` the correct choice for a single-command plaintext password set.

How to eliminate wrong answers

Option A is wrong because `passwd` does not accept the password as a command-line argument; it prompts interactively or reads from stdin, and passing the password directly would expose it in the process list and is not supported. Option C is wrong because `useradd -p` expects a hashed password string, not a plaintext password; using a plaintext password here would either fail or store an invalid hash, and the password would not be set correctly. Option D is wrong because `usermod -p` also expects a hashed password, not plaintext, and the command would not set the password as intended; additionally, `usermod` modifies an existing user, not creating a new one.

Page 1 of 3 · 151 questions totalNext →

Ready to test yourself?

Try a timed practice session using only Scripting Containers questions.