Demurrage is charged while a full container stays at the port or CFS beyond its free days. Detention is charged while you keep the shipping line's container outside the port beyond its free days, until the empty is returned. Both run per container, per day, and both can be avoided with early warning.
Once your import container is discharged, the line and the terminal or CFS allow a number of free days. If the full container is still there when they run out, demurrage (and usually ground rent or storage) starts. Common causes are late documents, customs queries, pending duty payment and no truck booked.
After you take the full container out, the clock keeps running on the box itself. Detention starts if the empty is not returned to the line's yard before the free days end. Slow destuffing at the warehouse and long empty-return queues are the usual causes.
Free days depend on the line, your contract and the port, so read them from your BL terms or rate agreement rather than assuming. Some lines combine demurrage and detention into one allowance; others count them separately. Charges usually rise in slabs, so day 10 costs more than day 4.
Most charges come from finding out too late. File the bill of entry early, keep duty funds ready, book transport as soon as the vessel's ETA firms up, and destuff quickly so the empty goes back on time.
When every container shows its discharge date, free days used and days left, your team can act on the boxes close to their limit instead of discovering the invoice later.